Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19]
Example 2:
Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44]
Constraints:
1 <= arr1.length, arr2.length <= 10000 <= arr1[i], arr2[i] <= 1000arr2 are distinct.arr2[i] is in arr1.Problem summary: Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[2,3,1,3,2,4,6,7,9,2,19] [2,1,4,3,9,6]
[28,6,22,8,44,17] [22,28,8,6]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1122: Relative Sort Array
class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map<Integer, Integer> pos = new HashMap<>(arr2.length);
for (int i = 0; i < arr2.length; ++i) {
pos.put(arr2[i], i);
}
int[][] arr = new int[arr1.length][0];
for (int i = 0; i < arr.length; ++i) {
arr[i] = new int[] {arr1[i], pos.getOrDefault(arr1[i], arr2.length + arr1[i])};
}
Arrays.sort(arr, (a, b) -> a[1] - b[1]);
for (int i = 0; i < arr.length; ++i) {
arr1[i] = arr[i][0];
}
return arr1;
}
}
// Accepted solution for LeetCode #1122: Relative Sort Array
func relativeSortArray(arr1 []int, arr2 []int) []int {
pos := map[int]int{}
for i, x := range arr2 {
pos[x] = i
}
arr := make([][2]int, len(arr1))
for i, x := range arr1 {
if p, ok := pos[x]; ok {
arr[i] = [2]int{p, x}
} else {
arr[i] = [2]int{len(arr2), x}
}
}
sort.Slice(arr, func(i, j int) bool {
return arr[i][0] < arr[j][0] || arr[i][0] == arr[j][0] && arr[i][1] < arr[j][1]
})
for i, x := range arr {
arr1[i] = x[1]
}
return arr1
}
# Accepted solution for LeetCode #1122: Relative Sort Array
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
pos = {x: i for i, x in enumerate(arr2)}
return sorted(arr1, key=lambda x: pos.get(x, 1000 + x))
// Accepted solution for LeetCode #1122: Relative Sort Array
struct Solution;
use std::cmp::Ordering;
use std::collections::HashMap;
impl Solution {
fn relative_sort_array(mut arr1: Vec<i32>, arr2: Vec<i32>) -> Vec<i32> {
let mut hm: HashMap<i32, usize> = HashMap::new();
for (i, &v) in arr2.iter().enumerate() {
hm.insert(v, i);
}
arr1.sort_by(|a, b| match (hm.get(a), hm.get(b)) {
(Some(i), Some(j)) => i.cmp(j),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => a.cmp(b),
});
arr1
}
}
#[test]
fn test() {
let arr1 = vec![2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19];
let arr2 = vec![2, 1, 4, 3, 9, 6];
let res = vec![2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19];
assert_eq!(Solution::relative_sort_array(arr1, arr2), res);
}
// Accepted solution for LeetCode #1122: Relative Sort Array
function relativeSortArray(arr1: number[], arr2: number[]): number[] {
const pos: Map<number, number> = new Map();
for (let i = 0; i < arr2.length; ++i) {
pos.set(arr2[i], i);
}
const arr: number[][] = [];
for (const x of arr1) {
const j = pos.get(x) ?? arr2.length;
arr.push([j, x]);
}
arr.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
return arr.map(a => a[1]);
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.