diff --git a/0001_TwoSum_HashMap.java b/0001_TwoSum_HashMap.java new file mode 100644 index 0000000..691a685 --- /dev/null +++ b/0001_TwoSum_HashMap.java @@ -0,0 +1,17 @@ +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap 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[] {}; + } +} diff --git a/0128_Longest_Consecutive_Sequence.java b/0128_Longest_Consecutive_Sequence.java new file mode 100644 index 0000000..65c0494 --- /dev/null +++ b/0128_Longest_Consecutive_Sequence.java @@ -0,0 +1,34 @@ +import java.util.HashSet; + +class Solution { + public int longestConsecutive(int[] nums) { + + HashSet set = new HashSet<>(); + + // Add all numbers to set + for (int num : nums) { + set.add(num); + } + + int longest = 0; + + for (int num : set) { + + // Check if it's the start of a sequence + if (!set.contains(num - 1)) { + + int currentNum = num; + int currentStreak = 1; + + while (set.contains(currentNum + 1)) { + currentNum++; + currentStreak++; + } + + longest = Math.max(longest, currentStreak); + } + } + + return longest; + } +} diff --git a/README.md b/README.md index d7fc5fb..bd25c9f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,23 @@ +# Hashing + +## 1. Two Sum +Problem Link: https://leetcode.com/problems/two-sum/ +Difficulty: Easy +### Approach : HashMap (Optimized) +Time Complexity: O(n) +Space Complexity: O(n) +### Concepts Used: +Array Traversal,HashMap,Complement Technique,Single Pass Algorithm,Key-Value Mapping + +## 128. Longest Consecutive Sequence +Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ +Difficulty: Medium +### Approach: HashSet (Optimized) +Time Complexity: O(n) +Space Complexity: O(n) +### Concepts Used: +HashSet, Sequence Pattern, Array Traversal +======= # Prefix-Sum ## 523. Continuous Subarray Sum