Problem Statement
Build Array from Permutation - LeetCode
Pattern: Pattern 2 values in 1 variable
Solution
public int[] buildArray(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
// nums[nums[i]] is the supposed correct location of nums[i]
// nums[nums[i]] % n reverses this 👇 black magic we did to it, in case we did, otherwise same value.
nums[i] = nums[i] + n * (nums[nums[i]] % n);
// to store a and b in a
// a' = a + (b * k) - where k is some constant larger than both a and b, in this case we use nums.length
// how are both a and b stored in a?
// well a' % k will give you a
// a' / k will give you b !!
}
for (int i = 0; i < n; i++) {
nums[i] = nums[i] / n;
}
return nums;
}
Notes
- The whole idea is to store 2 number inside of a single number
- reversing black magic : restores the earlier number if it has already been altered