↓Skip to main content
  1. LeetCode/

LeetCode 1122: Relative Sort Array

·1 min· ·
LeetCode Easy Array Hash-Table Sorting Counting-Sort
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-10-18

  • Submissions: Wrong Answer ×2 → Accepted ×2

Approach
#

Count arr1 with a Counter (Hash Table Template 1). Following arr2, emit each value as many times as it appears and remove it from the counts. Append the values not in arr2 in ascending order with their multiplicities. With values in 0..1000, a size-1001 counting array also works.

My Attempts
#

  • Attempt 1 emitted the leftovers with C.most_common(), ordered by frequency rather than value: [6, 0, 9], [9] returned [9, 6, 0] instead of [9, 0, 6].
  • Attempt 2 used sorted(C.keys()), correctly ordered but with each value only once: [2, 2, 6], [6] returned [6, 2]. sorted(C.elements()) passed.

Solution
#

class Solution:
    def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
        cnt = Counter(arr1)
        res = []
        for x in arr2:
            res += [x] * cnt.pop(x)
        for x in sorted(cnt):
            res += [x] * cnt[x]
        return res

Complexity
#

Time O(n + k log k), space O(n).

Mistakes to Avoid
#

  • The remaining values go in ascending order, not by frequency.
  • Keep the remaining values’ multiplicities.

Interview Explanation
#

I count first, emit arr2’s values in order with their counts, then append the remaining values ascending with their counts. Time O(n + k log k).

Related

LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 1051: Height Checker
·1 min
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 note: sort and count the positions that differ from the original