Two Sum Problem Solution with Brute Force and HashMap Approaches

Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution {   public int[] twoSum(int[] nums, int target) {   for (int i = 0; i < nums.length; i++) {  for (int j = i + 1; j < nums.length; j++) {   if (nums[i] + nums[j] == target) {   return new int[]{i, j};  }   }  }   return new int[]{};   } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) 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[]{};  } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories