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.
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:
nums in non-increasing order.
nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order.nums in non-decreasing order.
nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order.Return the array formed after rearranging the values of nums.
Example 1:
Input: nums = [4,1,2,3] Output: [2,3,4,1] Explanation: First, we sort the values present at odd indices (1 and 3) in non-increasing order. So, nums changes from [4,1,2,3] to [4,3,2,1]. Next, we sort the values present at even indices (0 and 2) in non-decreasing order. So, nums changes from [4,1,2,3] to [2,3,4,1]. Thus, the array formed after rearranging the values is [2,3,4,1].
Example 2:
Input: nums = [2,1] Output: [2,1] Explanation: Since there is exactly one odd index and one even index, no rearrangement of values takes place. The resultant array formed is [2,1], which is the same as the initial array.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100Problem summary: You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Sort the values at odd indices of nums in non-increasing order. For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order. Sort the values at even indices of nums in non-decreasing order. For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order. Return the array formed after rearranging the values of nums.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[4,1,2,3]
[2,1]
sort-array-by-parity)sort-array-by-parity-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2164: Sort Even and Odd Indices Independently
class Solution {
public int[] sortEvenOdd(int[] nums) {
int n = nums.length;
int[] a = new int[(n + 1) >> 1];
int[] b = new int[n >> 1];
for (int i = 0, j = 0; j < n >> 1; i += 2, ++j) {
a[j] = nums[i];
b[j] = nums[i + 1];
}
if (n % 2 == 1) {
a[a.length - 1] = nums[n - 1];
}
Arrays.sort(a);
Arrays.sort(b);
int[] ans = new int[n];
for (int i = 0, j = 0; j < a.length; i += 2, ++j) {
ans[i] = a[j];
}
for (int i = 1, j = b.length - 1; j >= 0; i += 2, --j) {
ans[i] = b[j];
}
return ans;
}
}
// Accepted solution for LeetCode #2164: Sort Even and Odd Indices Independently
func sortEvenOdd(nums []int) []int {
n := len(nums)
var a []int
var b []int
for i, v := range nums {
if i%2 == 0 {
a = append(a, v)
} else {
b = append(b, v)
}
}
ans := make([]int, n)
sort.Ints(a)
sort.Slice(b, func(i, j int) bool {
return b[i] > b[j]
})
for i, j := 0, 0; j < len(a); i, j = i+2, j+1 {
ans[i] = a[j]
}
for i, j := 1, 0; j < len(b); i, j = i+2, j+1 {
ans[i] = b[j]
}
return ans
}
# Accepted solution for LeetCode #2164: Sort Even and Odd Indices Independently
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
a = sorted(nums[::2])
b = sorted(nums[1::2], reverse=True)
nums[::2] = a
nums[1::2] = b
return nums
// Accepted solution for LeetCode #2164: Sort Even and Odd Indices Independently
/**
* [2164] Sort Even and Odd Indices Independently
*
* You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:
* <ol>
* Sort the values at odd indices of nums in non-increasing order.
*
* For example, if nums = [4,<u>1</u>,2,<u>3</u>] before this step, it becomes [4,<u>3</u>,2,<u>1</u>] after. The values at odd indices 1 and 3 are sorted in non-increasing order.
*
*
* Sort the values at even indices of nums in non-decreasing order.
*
* For example, if nums = [<u>4</u>,1,<u>2</u>,3] before this step, it becomes [<u>2</u>,1,<u>4</u>,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order.
*
*
* </ol>
* Return the array formed after rearranging the values of nums.
*
* Example 1:
*
* Input: nums = [4,1,2,3]
* Output: [2,3,4,1]
* Explanation:
* First, we sort the values present at odd indices (1 and 3) in non-increasing order.
* So, nums changes from [4,<u>1</u>,2,<u>3</u>] to [4,<u>3</u>,2,<u>1</u>].
* Next, we sort the values present at even indices (0 and 2) in non-decreasing order.
* So, nums changes from [<u>4</u>,1,<u>2</u>,3] to [<u>2</u>,3,<u>4</u>,1].
* Thus, the array formed after rearranging the values is [2,3,4,1].
*
* Example 2:
*
* Input: nums = [2,1]
* Output: [2,1]
* Explanation:
* Since there is exactly one odd index and one even index, no rearrangement of values takes place.
* The resultant array formed is [2,1], which is the same as the initial array.
*
*
* Constraints:
*
* 1 <= nums.length <= 100
* 1 <= nums[i] <= 100
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/sort-even-and-odd-indices-independently/
// discuss: https://leetcode.com/problems/sort-even-and-odd-indices-independently/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn sort_even_odd(nums: Vec<i32>) -> Vec<i32> {
let mut result = vec![];
let mut even: Vec<i32> = nums.iter().step_by(2).map(|&x| x).collect();
even.sort_by(|a, b| a.cmp(&b));
let mut e = even.iter();
let mut odd: Vec<i32> = nums.iter().skip(1).step_by(2).map(|&x| x).collect();
odd.sort_by(|a, b| b.cmp(&a));
let mut o = odd.iter();
for i in 0..nums.len() {
match i % 2 {
0 => result.push(*e.next().unwrap()),
_ => result.push(*o.next().unwrap()),
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2164_example_1() {
let nums = vec![4, 1, 2, 3];
let result = vec![2, 3, 4, 1];
assert_eq!(Solution::sort_even_odd(nums), result);
}
#[test]
fn test_2164_example_2() {
let nums = vec![2, 1];
let result = vec![2, 1];
assert_eq!(Solution::sort_even_odd(nums), result);
}
}
// Accepted solution for LeetCode #2164: Sort Even and Odd Indices Independently
function sortEvenOdd(nums: number[]): number[] {
const n = nums.length;
const a: number[] = [];
const b: number[] = [];
for (let i = 0; i < n; ++i) {
if (i % 2 === 0) {
a.push(nums[i]);
} else {
b.push(nums[i]);
}
}
a.sort((x, y) => x - y);
b.sort((x, y) => y - x);
const ans: number[] = [];
for (let i = 0, j = 0; j < a.length; i += 2, ++j) {
ans[i] = a[j];
}
for (let i = 1, j = 0; j < b.length; i += 2, ++j) {
ans[i] = b[j];
}
return ans;
}
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.