15% off all plans & roadmaps Use code

See plans

Distant Barcodes

Updated

TL;DR: You must reorder the barcodes so no two neighbours match, and the problem guarantees a valid order exists. Always place the two most frequent remaining values next to each other as a pair, using a max heap of counts.

Problem

In a warehouse, there is a row of barcodes. The ith barcode is barcodes[i].

Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any valid answer. The problem guarantees that at least one answer exists.

Example 1

Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

Example 2

Input: barcodes = [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,1,2,1,2]

Constraints

  • 1 <= barcodes.length <= 10000
  • 1 <= barcodes[i] <= 10000

Constraints that matter

  • barcodes.length up to 10000 rules out trying arrangements one by one, since the number of arrangements grows factorially. You need a method that runs in about n log n time.
  • Values go up to 10000, so a hash map of counts works. An array indexed by value would also fit.
  • The guarantee that an answer exists means the most frequent value appears at most ceil(n / 2) times. Your greedy never has to build an impossible arrangement, so it only needs to avoid collisions.

View on LeetCode

Hints

Hint 1

The hard value is the most frequent one, because every copy of it needs a different value on each side.

Hint 2

Count each value, then keep the values in a max heap ordered by remaining count.

Solution

Intuition

The hard value is the most frequent one, because every copy of it needs a different value on each side. If you delay placing it, the remaining values run out and the copies end up touching. So the rule is to spend the most common values first, the same way a task scheduler runs the busiest task early.

Picture a line of people waiting to be seated at two-person tables, where the group with the most members still waiting goes first. The heap is that line, and each table seats two different groups, so no table ever has duplicates.

The naive method tries every value at every slot and rejects any value equal to its neighbour. That search can visit almost every arrangement, which is far too many for n = 10000. Sorting the counts once does not help, because the choice at each slot changes as counts drop. You need the current most frequent value at each step, and a max heap gives you that in O(log k) time after each update.

Placing two values per round is the trick that makes the boundaries safe. You pop the top two values and write them at positions 2k and 2k + 1, so they are always different. The value that went first in a pair always has a count at least as high as the value that went second. So the second value can never rank first in the next round, and it cannot touch the start of the next pair.

Watch the pattern animation

Worked example

Input: barcodes = [2, 2, 2, 2, 3, 3, 4]
Output: [2, 3, 2, 3, 2, 4, 2]
Explanation: The value 2 appears 4 times, 3 appears 2 times and 4 appears once. The output places 2 in every even index, which is the only way to fit four copies of 2 into seven slots without touching. The 3s and the 4 fill the odd slots, and no two neighbours match. Another valid answer exists, but this output is the one the checker accepts.

The Task Scheduling (Frequency Based) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Task Scheduling (Frequency Based)

Part of Greedy Patterns

Approach 1: Max heap, taking pairsOptimalTask Scheduling (Frequency Based)

Count each value, then keep the values in a max heap ordered by remaining count. Each round pops the two most frequent values and writes them as a pair, so the pair always holds two different values. Pushing back the leftovers keeps the most common value spread across the result. Any final leftover value goes at the end.

Steps

  1. Build a hash map from each value to its count.
  2. Push each distinct value into a max heap keyed by count, with ties broken by value.
  3. While the heap holds at least two entries, pop the top two: call them first and second.
  4. Append first's value, then second's value, to the result.
  5. Subtract one from each count. Push an entry back only if its remaining count is greater than 0.
  6. When one entry is left, append its value. Its count must be 1 because the input is guaranteed solvable.
  7. Return the result.

Dry run

Each row below is one round of the loop on [2, 2, 2, 2, 3, 3, 4]. Counts are written as value:count.

RoundHeap beforePoppedResult after roundPushed back
12:4, 3:2, 4:12 (4), 3 (2)[2, 3]2:3, 3:1
22:3, 3:1, 4:12 (3), 3 (1)[2, 3, 2, 3]2:2 (3 drops to 0, not pushed)
32:2, 4:12 (2), 4 (1)[2, 3, 2, 3, 2, 4]2:1 (4 drops to 0, not pushed)
42:12 (1), alone[2, 3, 2, 3, 2, 4, 2]nothing

The heap is empty and the result matches the example output.

Complexity

TimeO(n log k)
SpaceO(n)

Let n be the array length and k the number of distinct values, so k is at most n. Counting takes one pass, O(n). Each round places two values and does at most four heap operations, and there are about n / 2 rounds, so the loop does O(n) heap operations on a heap of size at most k, each costing O(log k). The map and heap store up to k entries and the result stores n values, so the space is O(n) because k is at most n.

PythonTested in our runner

import heapq
from collections import Counter
from typing import List, Optional

class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        counts = Counter(barcodes)
        # heapq is a min-heap, so store negative counts to pop the largest first
        heap = [(-count, value) for value, count in counts.items()]
        heapq.heapify(heap)
        result = []
        while len(heap) >= 2:
            neg1, v1 = heapq.heappop(heap)
            neg2, v2 = heapq.heappop(heap)
            result.append(v1)
            result.append(v2)
            # push back only values that still have copies left
            if neg1 + 1 < 0:
                heapq.heappush(heap, (neg1 + 1, v1))
            if neg2 + 1 < 0:
                heapq.heappush(heap, (neg2 + 1, v2))
        if heap:
            result.append(heap[0][1])
        return result

Common mistakes

  • Pushing the first value back before popping the second, as in heap.push(first) followed by heap.pop(). The pop can return the same value, so the pair repeats a value. Pop both values first, then push back.
  • Pushing back values whose count has reached 0, for example if first.count >= 0. A spent value then returns to the heap and gets placed again. Push back only when the remaining count is greater than 0.
  • Using a Python heapq with positive counts, as in (count, value). The min-heap then returns the least frequent value first, which breaks the greedy choice. Store negative counts.
  • Writing only pairs and forgetting the last value when the number of distinct values is odd in the final round. The result comes out one element short. After the loop, append the single remaining value.
  • Changing a count inside the heap while the entry is still stored, for example heap.top().first-- in C++ or mutating an array that the heap already holds in Java. The heap order breaks silently. Pop the entry, change the copy, then push it again.
  • Building the result from the counts map instead of the heap order, for example by appending each value count times in map order. That puts equal values next to each other. The order must come from repeated heap pops.

Edge cases

  • A single barcode, [7], returns [7] because the loop never runs and the leftover branch appends the only value.
  • Two different values with equal counts, [1, 2], returns [1, 2] as one pair.
  • A value that is exactly half the array, [1, 1, 2, 2], returns [1, 2, 1, 2]. The heap pushes each value back once and both rounds alternate correctly.
  • A dominant value at odd length, [1, 1, 2], returns [1, 2, 1]. The leftover branch appends the last copy of 1 after the pair.
  • All values distinct, [1, 2, 3, ..., 10000], returns the values in heap order. Every count is 1, so no value is pushed back and the heap empties in n / 2 rounds.
  • Maximum size with a large frequency, such as 5000 copies of 1 and 5000 copies of 2, returns an alternating sequence of length 10000 with no adjacent duplicates.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Distant Barcodes, with how to answer them.

Unlock the follow-ups

Distant Barcodes FAQ

What is the time complexity of Distant Barcodes?

The time complexity is O(n log k), where n is the array length and k is the number of distinct values. Since k is at most n, this is at most O(n log n). Counting takes O(n), and each of the about n / 2 rounds does a constant number of heap operations.

Why use a max heap for Distant Barcodes?

The rule is to place the most frequent remaining value at each round, and counts change after every round. A max heap returns the largest count in O(log k) time and accepts updates at the same cost. A sorted list would need a full re-sort after each change.

Can Distant Barcodes be solved in O(1) extra space?

No, not with the heap approach. It stores one entry per distinct value, so the extra space grows with k, up to n. Only a constant bound on value range makes the counts a fixed size.

Why does pairing the two most frequent values avoid adjacent duplicates?

Each pair holds two different values because the heap contains each value once. The value in the first slot of a pair always has a count at least as high as the second, so it cannot rank first in the next round. That blocks the boundary collision between one pair and the next.

Why does Python need negative counts for this problem?

Python's heapq module is a min-heap, so the smallest tuple comes out first. Storing the count as a negative number makes the most frequent value the smallest tuple. Forgetting this sends the least frequent value to the front.

Asked at

See which companies ask this — Pro

Practise it