From 9efc587087cae09ea640ebe6f21203b30b71081e Mon Sep 17 00:00:00 2001 From: yashhh-23 Date: Wed, 8 Jul 2026 18:22:05 +0530 Subject: [PATCH] completed comeptitive coding - 2 --- Problem1.java | 0 twosum.java | 24 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+) delete mode 100644 Problem1.java create mode 100644 twosum.java diff --git a/Problem1.java b/Problem1.java deleted file mode 100644 index e69de29b..00000000 diff --git a/twosum.java b/twosum.java new file mode 100644 index 00000000..69386c35 --- /dev/null +++ b/twosum.java @@ -0,0 +1,24 @@ +// Time Complexity : O(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : difficult to come up with the approach of using hashmap to store the values and their indices. +// Your code here along with comments explaining your approach: hashmap is used to store the values and their indices. In the first loop, we store all the values and their indices in the hashmap. In the second loop, we check if the complement of the current value (target - current value) exists in the hashmap and if it does, we return the indices of the two values. +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap map = new HashMap<>(); + + for(int i = 0; i < nums.length; i++) { + map.put(nums[i], i); + } + + for (int i = 0; i < nums.length; i++) { + int cmp = target - nums[i]; + if (map.containsKey(cmp) && map.get(cmp) != i) { + return new int[]{map.get(cmp),i}; + } + map.put(nums[i], i); + } + + return new int[]{}; + } +} \ No newline at end of file