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 a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
1 <= nums.length <= 3 * 104-3 * 104 <= nums[i] <= 3 * 104Problem summary: Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Bit Manipulation
[2,2,1]
[4,1,2,1,2]
[1]
single-number-ii)single-number-iii)missing-number)find-the-duplicate-number)find-the-difference)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #136: Single Number
class Solution {
public int singleNumber(int[] nums) {
int ans = 0;
for (int v : nums) {
ans ^= v;
}
return ans;
}
}
// Accepted solution for LeetCode #136: Single Number
func singleNumber(nums []int) (ans int) {
for _, v := range nums {
ans ^= v
}
return
}
# Accepted solution for LeetCode #136: Single Number
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(xor, nums)
// Accepted solution for LeetCode #136: Single Number
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
nums.into_iter().reduce(|r, v| r ^ v).unwrap()
}
}
// Accepted solution for LeetCode #136: Single Number
function singleNumber(nums: number[]): number {
return nums.reduce((r, v) => r ^ v);
}
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
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.