#2122

Recover the Original Array

Hard
ArrayHash TableTwo PointersSortingEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

We can use a HashMap to count occurrences of each number and derive k directly from the smallest element. This reduces unnecessary checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the occurrences of each number in nums using a HashMap.
  2. 2Step 2: Iterate through the unique numbers and calculate potential k values based on the smallest number.
  3. 3Step 3: For each k, check if we can form the original array by ensuring that for every lower[i], there exists a higher[i].
solution.py12 lines
1from collections import Counter
2
3def recoverArray(nums):
4    count = Counter(nums)
5    n = len(nums) // 2
6    for num in sorted(count.keys()):
7        k = (count[num] + 1) // 2
8        lower = num - k
9        higher = num + k
10        if count[lower] >= k and count[higher] >= k:
11            return [lower] * k + [higher] * k
12    return []

Complexity note: The time complexity is O(n log n) due to sorting the unique elements of nums, and the space complexity is O(n) for storing counts.

  • 1The relationship between lower, higher, and the original array arr is crucial to derive k.
  • 2Sorting the input helps in easily finding pairs and managing counts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.