Algorithm_Day01_Two Sum_lc#1
π§© Problem Description
Given an array of integers nums
and an integer target
, return the indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
π‘ Naive Approach (Brute Force)
The most straightforward idea is to check all pairs using two nested loops.
This guarantees we find the solution, but itβs inefficient for large arrays.
π’ Java Code β Brute Force
1 | class Solution { |
β± Complexity
- Time Complexity: O(nΒ²)
- Space Complexity: O(1)
β οΈ This solution does not scale β it fails performance constraints on large inputs.
π‘ Optimized Approach (Hash Map)
To reduce time complexity, we use a hash map to store values weβve seen and their indices.
While iterating, we check whether target - current
has already been seen.
π Key Points
- In practice, hash tables are fast β usually O(1) for most operations.
- Worst case happens when many keys collide (bad hash function or high load factor).
- Javaβs
HashMap
uses a red-black tree (Deeper explanation will be covered in a future post.) for long collision chains (O(log n) worst case for search).
π’ Java Code β Hash Map
1 | class Solution { |
β± Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
β Efficient and suitable for large datasets.
βοΈ Summary
- Always start with brute force to validate your logic.
- Then optimize using data structures like hash maps.