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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:
nums that are strictly less than instructions[i].nums that are strictly greater than instructions[i].For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].
Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7
Example 1:
Input: instructions = [1,5,6,2] Output: 1 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 5 with cost min(1, 0) = 0, now nums = [1,5]. Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6]. Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6]. The total cost is 0 + 0 + 0 + 1 = 1.
Example 2:
Input: instructions = [1,2,3,6,5,4] Output: 3 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 2 with cost min(1, 0) = 0, now nums = [1,2]. Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3]. Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6]. Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6]. Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6]. The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
Example 3:
Input: instructions = [1,3,3,3,2,4,2,1,2] Output: 4 Explanation: Begin with nums = []. Insert 1 with cost min(0, 0) = 0, now nums = [1]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3]. Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3]. Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3]. Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4]. Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4]. Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4]. Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4]. The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
Constraints:
1 <= instructions.length <= 1051 <= instructions[i] <= 105Problem summary: Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following: The number of elements currently in nums that are strictly less than instructions[i]. The number of elements currently in nums that are strictly greater than instructions[i]. For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Segment Tree
[1,5,6,2]
[1,2,3,6,5,4]
[1,3,3,3,2,4,2,1,2]
count-good-triplets-in-an-array)longest-substring-of-one-repeating-character)sort-array-by-moving-items-to-empty-space)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1649: Create Sorted Array through Instructions
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
this.c = new int[n + 1];
}
public void update(int x, int v) {
while (x <= n) {
c[x] += v;
x += x & -x;
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= x & -x;
}
return s;
}
}
class Solution {
public int createSortedArray(int[] instructions) {
int m = 0;
for (int x : instructions) {
m = Math.max(m, x);
}
BinaryIndexedTree tree = new BinaryIndexedTree(m);
int ans = 0;
final int mod = (int) 1e9 + 7;
for (int i = 0; i < instructions.length; ++i) {
int x = instructions[i];
int cost = Math.min(tree.query(x - 1), i - tree.query(x));
ans = (ans + cost) % mod;
tree.update(x, 1);
}
return ans;
}
}
// Accepted solution for LeetCode #1649: Create Sorted Array through Instructions
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) update(x, delta int) {
for x <= this.n {
this.c[x] += delta
x += x & -x
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= x & -x
}
return s
}
func createSortedArray(instructions []int) (ans int) {
m := slices.Max(instructions)
tree := newBinaryIndexedTree(m)
const mod = 1e9 + 7
for i, x := range instructions {
cost := min(tree.query(x-1), i-tree.query(x))
ans = (ans + cost) % mod
tree.update(x, 1)
}
return
}
# Accepted solution for LeetCode #1649: Create Sorted Array through Instructions
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] += v
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def createSortedArray(self, instructions: List[int]) -> int:
m = max(instructions)
tree = BinaryIndexedTree(m)
ans = 0
mod = 10**9 + 7
for i, x in enumerate(instructions):
cost = min(tree.query(x - 1), i - tree.query(x))
ans += cost
tree.update(x, 1)
return ans % mod
// Accepted solution for LeetCode #1649: Create Sorted Array through Instructions
/**
* [1649] Create Sorted Array through Instructions
*
* Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:
*
*
* The number of elements currently in nums that are strictly less than instructions[i].
* The number of elements currently in nums that are strictly greater than instructions[i].
*
*
* For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].
*
* Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 10^9 + 7
*
*
* Example 1:
*
*
* Input: instructions = [1,5,6,2]
* Output: 1
* Explanation: Begin with nums = [].
* Insert 1 with cost min(0, 0) = 0, now nums = [1].
* Insert 5 with cost min(1, 0) = 0, now nums = [1,5].
* Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].
* Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].
* The total cost is 0 + 0 + 0 + 1 = 1.
*
* Example 2:
*
*
* Input: instructions = [1,2,3,6,5,4]
* Output: 3
* Explanation: Begin with nums = [].
* Insert 1 with cost min(0, 0) = 0, now nums = [1].
* Insert 2 with cost min(1, 0) = 0, now nums = [1,2].
* Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].
* Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].
* Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].
* Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].
* The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
*
*
* Example 3:
*
*
* Input: instructions = [1,3,3,3,2,4,2,1,2]
* Output: 4
* Explanation: Begin with nums = [].
* Insert 1 with cost min(0, 0) = 0, now nums = [1].
* Insert 3 with cost min(1, 0) = 0, now nums = [1,3].
* Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].
* Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].
* Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].
* Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].
* Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].
* Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].
* Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].
* The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
*
*
*
* Constraints:
*
*
* 1 <= instructions.length <= 10^5
* 1 <= instructions[i] <= 10^5
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/create-sorted-array-through-instructions/
// discuss: https://leetcode.com/problems/create-sorted-array-through-instructions/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
const MOD: i32 = 1_000_000_007;
impl Solution {
// Credit: https://leetcode.com/problems/create-sorted-array-through-instructions/solutions/3183547/just-a-runnable-solution/
pub fn create_sorted_array(instructions: Vec<i32>) -> i32 {
let mut c = vec![0; 100001];
let mut res = 0;
let n = instructions.len();
for (i, &item) in instructions.iter().enumerate().take(n) {
let v1 = Self::get(&c, item - 1);
let v2 = i as i32 - Self::get(&c, item);
res = (res + v1.min(v2)) % MOD;
Self::update(&mut c, item);
}
res
}
fn update(c: &mut [i32], x: i32) {
let mut x = x as usize;
while x < 100001 {
c[x] += 1;
x += x & x.wrapping_neg();
}
}
fn get(c: &[i32], x: i32) -> i32 {
let mut x = x as usize;
let mut res = 0;
while x > 0 {
res += c[x];
x -= x & x.wrapping_neg();
}
res
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1649_example_1() {
let instructions = vec![1, 5, 6, 2];
let result = 1;
assert_eq!(Solution::create_sorted_array(instructions), result);
}
#[test]
fn test_1649_example_2() {
let instructions = vec![1, 2, 3, 6, 5, 4];
let result = 3;
assert_eq!(Solution::create_sorted_array(instructions), result);
}
#[test]
fn test_1649_example_3() {
let instructions = vec![1, 3, 3, 3, 2, 4, 2, 1, 2];
let result = 4;
assert_eq!(Solution::create_sorted_array(instructions), result);
}
}
// Accepted solution for LeetCode #1649: Create Sorted Array through Instructions
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = new Array(n + 1).fill(0);
}
public update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] += v;
x += x & -x;
}
}
public query(x: number): number {
let s = 0;
while (x > 0) {
s += this.c[x];
x -= x & -x;
}
return s;
}
}
function createSortedArray(instructions: number[]): number {
const m = Math.max(...instructions);
const tree = new BinaryIndexedTree(m);
let ans = 0;
const mod = 10 ** 9 + 7;
for (let i = 0; i < instructions.length; ++i) {
const x = instructions[i];
const cost = Math.min(tree.query(x - 1), i - tree.query(x));
ans = (ans + cost) % mod;
tree.update(x, 1);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
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: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.