r/JavaProgramming • u/Antique-Ride-8337 • 4h ago
Day 2 of my Java & DSA Journey ā Solved Two Sum using HashMap (O(n))
Hi everyone!
This is Day 2 of my Java & DSA journey.
Today I practiced one of the most popular interview questions: Two Sum.
Problem
Given an array of integers and a target value, return the indices of the two numbers whose sum equals the target.
My Java Solution
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
}
What I learned today
- How
HashMaphelps reduce time complexity. - Difference between brute force
O(n²)and optimizedO(n). - Why storing previously seen values is useful.
I'm trying to improve my Java and DSA skills every day. If you have any tips for writing cleaner Java code or preparing for coding interviews, I'd love to hear them.
Thanks for reading!
