MediumArrayHash TableGreedySortingHeap (Priority Queue)Counting

Distant Barcodes

LeetCode
1 approach, code in all languages

In a warehouse, a row of barcodes is given as an integer array where barcodes[i] is the i-th barcode value. Rearrange the barcodes so that no two adjacent barcodes are equal.

A valid answer is guaranteed to exist. Return any arrangement that satisfies the rule.

Example 1

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

Output: [2,1,2,1,2,1]

Alternating the two values keeps equal barcodes from touching.

Example 2

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

Output: [1,3,1,3,1,2,1,2]

The value 1 is most frequent, so it takes alternating slots first, then the rest fill in without repeats.

Constraints

  • 1 <= barcodes.length <= 10^4
  • 1 <= barcodes[i] <= 10^4
  • A valid answer always exists.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now