#3668

Restore Finishing Order

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Use a hash set for quick lookups of friends' IDs, allowing us to filter the order array efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a hash set from the friends array for O(1) lookups.
  2. 2Step 2: Iterate through the order array and check if each ID is in the hash set.
  3. 3Step 3: Collect matching IDs into the result array.
solution.py3 lines
1def restore_order(order, friends):
2    friend_set = set(friends)
3    return [friend for friend in order if friend in friend_set]

Complexity note: Creating the hash set takes O(m) time, and filtering the order takes O(n), leading to linear complexity overall.

  • 1Using a hash set allows for faster lookups.
  • 2Filtering based on a set is more efficient than nested loops.

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