1. Nested Loops Pair Check (Brute Force)
Intuition
Run two nested loops: for each i from 0 to n-1, scan j from i+1 to n-1. If nums[i] == nums[j], add to duplicate list.
When to apply: Use to illustrate the baseline search without extra space.
Nested Loops Duplicate Check (O(N^2) Time)
2 of 2 questions left today4 appears only once
4 appears only once.
import java.util.*; public class Main { public static class Solution { public List<Integer> findDuplicates(int[] nums) { List<Integer> res = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] == nums[j]) { res.add(nums[i]); break; } } } return res; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {4, 3, 2, 7, 8, 2, 3, 1}; System.out.println("Duplicates: " + sol.findDuplicates(nums)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Nested loops examine all n*(n-1)/2 pairs. - Space complexity:
O(1) auxiliary— O(1) extra space outside the returned list.
Why Brute Force Doesn't Scale:
For embedded or memory-constrained environments with N = 100,000, allocating 100,000 hash nodes consumes several megabytes.
Sign negation modifies the sign bits in-place with 0 additional memory allocation.