Posts

Longest Substring Without Repeating Characters

 Given a string s, find the length of the longest substring without duplicate characters.   Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. class Solution {     public int lengthOfLongestSubstring ( String s ) {         int start = 0 ;         int maxLength = 0 ;         int n = s . length ();         HashSet < Character > set = new HashSet <>();         for ( int end = 0 ; end < n; end++) {             char ch = s . charAt (end);             // If char...

Valid Anagram

 Given two strings s and t, return true if t is an anagram of s, and false otherwise. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false   class Solution {     public boolean isAnagram ( String s , String t ) {           if ( s . length () != t . length ())   {     return false ;   } Map < Character , Integer > freq = new HashMap <>(); for ( char c : s . toCharArray ()) { freq . put (c, freq . getOrDefault (c, 0 )+ 1 ); } for ( char ch : t . toCharArray ()) { freq . put (ch, freq . getOrDefault (ch, 0 )- 1 ); }       for ( int count : freq . values ()) {             if (count != 0 ) return false ;         } return true ;     } }

Group Anagrams

 Given an array of strings strs, group the anagrams together. You can return the answer in any order.   Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Explanation: There is no string in strs that can be rearranged to form "bat". The strings "nat" and "tan" are anagrams as they can be rearranged to form each other. The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other. Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] class Solution {     public List < List < String >> groupAnagrams ( String [] strs ) {                   // Create a map to group the anagrams, where the key is the sorted string, and the value ...

Longest Consecutive Sequence

 Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.   Example 1: Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. Example 2: Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9 Example 3: Input: nums = [1,0,1,2] Output: 3   ✅ Step-by-Step Dry Run: 🔹 Step 1: Put all numbers into a set We create this: set = {100, 4, 200, 1, 3, 2} So we can quickly check if a number exists (in O(1) time). 🔹 Step 2: Loop through each number in the array 🔸 First number: 100 Check if 99 is in the set → ❌ No So 100 is the start of a sequence Start counting: 101 → ❌ not in set → Stop Sequence length = 1 longest = max(0, 1) = 1 🔸 Next: 4 Check if 3 is in the set → ✅ Yes So 4 is not a starting point → skip 🔸 Next: 200 Check if 199 is in the set → ❌ No So 200 ...

Container With Most Water 2 Pointer Approach

Image
 You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container.   Example 1: Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example 2: Input: height = [1,1] Output: 1   🧠 2. Two Pointer Approach (Simple Idea) Start with two pointers : Left pointer at start ( i = 0 ) Right pointer at end ( j = height.length - 1 ) While i < j : Calculate the current water area. Keep track of the maximum area found. Move the pointer with shorter height , because: Only moving the smaller line...

Design HashMap LeetCode

 Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class: MyHashMap() initializes the object with an empty map. void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.   Example 1: Input ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] Output [null, null, null, 1, -1, null, 1, null, -1] Explanation MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now [[1,1]] myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] myHashMap.get(1);    // return 1,...

Valid Triangle Number

 Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Example 1: Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are:  2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Example 2: Input: nums = [4,2,3,4] Output: 4 class Solution {     public int triangleNumber ( int [] nums ) {                     Arrays . sort (nums); // Step 1: sort the array         int count = 0 ;         int n = nums . length ;         // Step 2: fix the largest side         for ( int k = n - 1 ; k >= 2 ; k--) {             int start = 0 ;             int end = k - 1 ;             // Step 3: use two pointers         ...

4Sum

 Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < n a, b, c, and d are distinct. nums[a] + nums[b] + nums[c] + nums[d] == target You may return the answer in any order.   Example 1: Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] Example 2: Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]] class Solution {     public List < List < Integer >> fourSum ( int [] nums , int target ) {                 List < List < Integer >> result = new ArrayList <>();         Arrays . sort (nums);         int n = nums . length ;         for ( int i = 0 ;i<n- 3 ;i++)         {             if (i > 0 && nums[i]==nums[i- 1 ]) continue ;   ...

3Sum LeetCode

 Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.   Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation:  nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.   code :1 import java.util.*; class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         List < List ...

Subarray Sum Equals K Leetcode

 Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2   Code : T.c o(n^2) class Solution {     public int subarraySum ( int [] nums , int k ) {                 // Variable to store the number of subarrays whose sum equals k         int count = 0 ;         // Loop through each starting point of the subarray         for ( int i = 0 ; i < nums . length ; i++) {             // Initialize prefix sum for this subarray starting at index i             int prefixsum = 0 ;             // Loop through each ending point of the subarray starting from ...