CMD Guide
HomeDSAAdvanced Patterns

easy Relative Sort Array

Problem Statement

Given two arrays arr1 of length n and arr2 of length m, sort the elements of arr1 such that the relative ordering of items in arr1 is the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.

It is given that elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Examples

Example 1:

Example 2:

Example 3:

Constraints:

Try it yourself

Try solving this question here:

🎯 STRICT STANDOUT — Relative Sort Array (problem)

0. Why this page exists

Family: Counting / custom-order sort

arr2 defines a partial order of keys that must appear first (with multiplicity from arr1); remaining keys ascending. Counting sort (values ≤1000) is the intended linear tool.

1. Pattern + when-NOT (K12)

Pattern / template: Count frequency of arr1. Emit counts in arr2 order (zeroing as you go). Then scan value domain ascending for leftovers. Equivalent: sort arr1 with comparator key=rank in arr2 else +∞+value — O(n log n).

When-NOT: When-NOT if values huge and sparse without hash+sort leftovers; when-NOT if arr2 not subset of arr1 (problem says it is). Prefer hash rank map + sort if n small and range huge.

2. Complexity derivation (K11)

Counting path: O(n + m + U) with U=1001 domain, m=|arr2|.
Comparator sort: O(n log n).
Constraints n,m≤1000, values≤1000 → counting is natural.

3. Edge hand-run (K13)

arr1=[3,5,2,1,6,4,5,6], arr2=[5,6,4,1] → [5,5,6,6,4,1,2,3].
All keys in arr2: no tail. Multiplicity only in arr1.
arr2 single key: that key's copies first, rest sorted.

4. Interviewer follow-ups & drills

Q1. Why counting over sort?
Model answer: Domain tiny; O(n+U) beats n log n and matches linear-sort theme.

Q2. Stability needed?
Model answer: Among equals order free except arr2 sequence and ascending tail.

Q3. arr2 has dup?
Model answer: Problem: arr2 elements distinct.

✅ Solution Relative Sort Array

Problem Statement

Given two arrays arr1 of length n and arr2 of length m, sort the elements of arr1 such that the relative ordering of items in arr1 is the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.

It is given that elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Examples

Example 1:

  • Input: arr1 = [3, 5, 2, 1, 6, 4, 5, 6], arr2 = [5, 6, 4, 1]
  • Expected Output: [5, 5, 6, 6, 4, 1, 2, 3]
  • Justification: Elements 5, 6, 4 and 1 from arr2 are placed in arr1 first in the same order as in arr2. The remaining elements 2 and 3 are placed at the end in ascending order.

Example 2:

  • Input: arr1 = [8, 3, 9, 1, 7, 5], arr2 = [3, 9, 8]
  • Expected Output: [3, 9, 8, 1, 5, 7]
  • Justification: Elements 3, 9 and 8 from arr2 are placed in arr1 first in the same order as in arr2. Remaining elements 1, 5 and 7 are placed at the end in ascending order.

Example 3:

  • Input: arr1 = [10, 10, 7, 10, 7, 9], arr2 = [10, 7]
  • Expected Output: [10, 10, 10, 7, 7, 9]
  • Justification: Elements 10 and 7 from arr2 are placed in arr1 first in the same order as in arr2. The remaining element 9 is placed at the end in ascending order.

Constraints:

  • 1 <= arr1.length, arr2.length <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • All the elements of arr2 are distinct.
  • Each arr2[i] is in arr1.

Solution

To solve this problem, we use a counting sort approach to arrange the elements of arr1 based on the order defined by arr2. First, we count the occurrences of each element in arr1 and store these counts in an array. Then, we use the counts to construct the sorted result by placing elements from arr2 in the specified order, followed by the remaining elements in ascending order.

This approach is effective because it leverages counting sort's efficiency for sorting integers when the range of values is not excessively large. By focusing on the order defined by arr2, we ensure that the relative ordering is maintained, and by appending the remaining elements in ascending order, we satisfy the problem's requirements.

Step-by-Step Algorithm

  1. Find Maximum Element:

    • Identify the largest element in arr1 to determine the size of the count array.
  2. Initialize Count Array:

    • Create an array count of size maxElement + 1 to store the frequency of each element in arr1.
    • The size is maxElement + 1 to accommodate the maximum element's index.
  3. Calculate the Frequency of each Element in arr1 Array:

    • Iterate through each element in arr1.
    • For each element, increment the corresponding index in the count array by 1.
    • This step counts the occurrences of each element in arr1.
  4. Create Result List:

    • Initialize an empty list result to store the sorted elements.
  5. Add Elements from arr2 to Result:

    • Iterate through each element in arr2.
    • For each element, append it to the result list as many times as it appears in the count array.
    • Decrement the corresponding index in the count array by 1 for each appended element.
    • This ensures that elements from arr2 appear in the result in the specified order.
  6. Add Remaining Elements to Result:

    • Iterate through the count array from index 0 to maxElement.
    • For each index with a positive count, append the index to the result list as many times as its count.
    • Decrement the count for each appended element.
    • This step ensures that remaining elements not in arr2 are appended in ascending order.
  7. Convert Result List to Array:

    • Convert the result list to an array and return it.

Algorithm Walkthrough

Image
Image
  • Input:
    • arr1 = [3, 5, 2, 1, 6, 4, 5, 6]
    • arr2 = [5, 6, 4, 1]
  1. Find Maximum Element:

    • maxElement is 6.
  2. Initialize Count Array:

    • count array is initialized to [0, 0, 0, 0, 0, 0, 0].
  3. Populate Count Array:

    • Iterate through arr1:
      • For 3: count becomes [0, 0, 0, 1, 0, 0, 0].
      • For 5: count becomes [0, 0, 0, 1, 0, 1, 0].
      • For 2: count becomes [0, 0, 1, 1, 0, 1, 0].
      • For 1: count becomes [0, 1, 1, 1, 0, 1, 0].
      • For 6: count becomes [0, 1, 1, 1, 0, 1, 1].
      • For 4: count becomes [0, 1, 1, 1, 1, 1, 1].
      • For 5: count becomes [0, 1, 1, 1, 1, 2, 1].
      • For 6: count becomes [0, 1, 1, 1, 1, 2, 2].
  4. Create Result List:

    • Initialize result as an empty list.
  5. Add Elements from arr2 to Result:

    • Iterate through arr2:
      • For 5: Append 5, count becomes [0, 1, 1, 1, 1, 1, 2], result becomes [5].
      • For 5: Append 5, count becomes [0, 1, 1, 1, 1, 0, 2], result becomes [5, 5].
      • For 6: Append 6, count becomes [0, 1, 1, 1, 1, 0, 1], result becomes [5, 5, 6].
      • For 6: Append 6, count becomes [0, 1, 1, 1, 1, 0, 0], result becomes [5, 5, 6, 6].
      • For 4: Append 4, count becomes [0, 1, 1, 1, 0, 0, 0], result becomes [5, 5, 6, 6, 4].
      • For 1: Append 1, count becomes [0, 0, 1, 1, 0, 0, 0], result becomes [5, 5, 6, 6, 4, 1].
  6. Add Remaining Elements to Result:

    • Iterate through the count array:
      • For 2: Append 2, count becomes [0, 0, 0, 1, 0, 0, 0], result becomes [5, 5, 6, 6, 4, 1, 2].
      • For 3: Append 3, count becomes [0, 0, 0, 0, 0, 0, 0], result becomes [5, 5, 6, 6, 4, 1, 2, 3].
  7. Convert Result List to Array:

    • result list is converted to array [5, 5, 6, 6, 4, 1, 2, 3].

Code

java
import java.util.*;

class Solution {

  public int[] relativeSortArray(int[] arr1, int[] arr2) {
    // Determine the largest value in arr1 to size the count array correctly
    int maxElement = Arrays.stream(arr1).max().orElse(0);
    // Create a count array to keep track of occurrences
    int[] count = new int[maxElement + 1];

    // Populate the count array with the frequency of each element in arr1
    for (int element : arr1) {
      count[element]++;
    }

    List<Integer> result = new ArrayList<>();
    // Append elements from arr2 to the result array, maintaining the given order
    for (int value : arr2) {
      while (count[value] > 0) {
        result.add(value);
        count[value]--;
      }
    }

    // Add the remaining elements that are not in arr2 to the result array in ascending order
    for (int num = 0; num <= maxElement; num++) {
      while (count[num] > 0) {
        result.add(num);
        count[num]--;
      }
    }

    // Convert the result ArrayList back to an array and return it
    return result.stream().mapToInt(Integer::intValue).toArray();
  }

  public static void main(String[] args) {
    Solution solution = new Solution();

    // Test case 1
    int[] arr1_1 = { 3, 5, 2, 1, 6, 4, 5, 6 };
    int[] arr2_1 = { 5, 6, 4, 1 };
    System.out.println(
      Arrays.toString(solution.relativeSortArray(arr1_1, arr2_1))
    ); // Expected Output: [5, 5, 6, 6, 4, 1, 2, 3]

    // Test case 2
    int[] arr1_2 = { 8, 3, 9, 1, 7, 5 };
    int[] arr2_2 = { 3, 9, 8 };
    System.out.println(
      Arrays.toString(solution.relativeSortArray(arr1_2, arr2_2))
    ); // Expected Output: [3, 9, 8, 1, 5, 7]

    // Test case 3
    int[] arr1_3 = { 10, 10, 7, 10, 7, 9 };
    int[] arr2_3 = { 10, 7 };
    System.out.println(
      Arrays.toString(solution.relativeSortArray(arr1_3, arr2_3))
    ); // Expected Output: [10, 10, 10, 7, 7, 9]
  }
}

Complexity Analysis

Time Complexity:

  • n: Length of arr1.
  • m: Length of arr2.
  • k: Maximum element in arr1.
  • We iterate through arr1 to populate the count array . Then, we iterate through arr2 to construct part of the result . Finally, we iterate through the count array to add remaining elements in ascending order . Hence, the total time complexity is .

Space Complexity:

  • k: Maximum element in arr1.
  • The space complexity is determined by the size of the count array, which is proportional to the maximum element in arr1. Thus, the space complexity is .

🎯 STRICT STANDOUT — Solution Relative Sort Array

0. Why this page exists

Family: Counting custom order

Solution should make the two-phase emit (arr2 order then domain scan) explicit and tie complexity to U=1000, not vague O(n).

1. Pattern + when-NOT (K12)

Pattern / template: freq[0..1000]; for x in arr1: freq[x]++. out=[]; for x in arr2: while freq[x]: out.append(x); freq[x]--. for v in 0..1000: while freq[v]: append.

When-NOT: When-NOT tree-map if interview forbids O(U) array — use HashMap + sort unique leftovers.

2. Complexity derivation (K11)

Time O(n + U + m) = O(n) under U constant 1001.
Space O(U) for freq (+ O(n) output).
Hand-run matches examples; no hidden n log n.

3. Edge hand-run (K13)

[10,10,7,10,7,9] / [10,7] → [10,10,10,7,7,9].
Empty arr1 → []. Values at 0 and 1000 endpoints of domain.

4. Interviewer follow-ups & drills

Q1. Where does leftover 9 go?
Model answer: After arr2 keys exhausted; domain scan hits 9.

Q2. Mutate arr1 in place?
Model answer: Possible with write index; same counts.

Q3. Transfer?
Model answer: Same histogram emit as counting-sort placement with custom order.

🧩 Pattern · Sorting

Recognize it: Order unlocks it (dedup, greedy-after-sort, two-pointer) → sort first, then scan.

▶ Visualize this problem (step it, predict each fork)
⛶ Open this problem debugger in explore mode
🤖 Don't fully get this? Learn it with Claude

Stuck on Relative Sort Array? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Relative Sort Array** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Relative Sort Array** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Relative Sort Array**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Relative Sort Array**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes