Bea.AI coding blog
  • Tree
    • Tree Traverse
    • Iteration based traverse
    • Typical problems and solutions
      • Max width of binary tree
      • Binary Tree & BST Serialize & Deserialize
      • Lowest common ancestor (LCA) for Binary Tree and BST
      • Subproblem-based Approach for Resolving Max Value on Trees
      • Path sum III
  • Graph
  • Data structure
    • Java data structure
  • Algorithm general templates
    • Tree
    • Trie
    • Graph
  • Java Algorithm Tips and Tricks
    • Java concurrent list
  • Coding patterns & Strategies
  • Coding patterns & template
    • 1. Binary Search
    • 2. Two Pointer
    • 3. Sliding Window
    • 4. Backtracking
    • 5. DFS
    • 6. BFS
    • 7. Stack
    • 8. Heap
    • 9. Prefix Sum
    • 10. Linked List
    • 11. BST
    • 12. Line sweep
    • 14. Tree
    • 15. Graph
    • 16. Bit manipulation
    • 17. Matrix
    • 18. Monotonic Stack
    • 19. Sorting
    • 20. Union Find
    • 21. Trie
    • 22. Dynamic programming
    • 23. Customized Data Structure
  • Code interview steps
  • Leetcode
    • Tree
      • Traversal
      • Construction and Conversion
      • Search and Validation
      • Manipulation and Modification
      • Special Trees
      • Miscellaneous
    • Dynamic programing
      • Classic DP Problems
      • Sequence/Array DP
      • Matrix DP
      • Knapsack Problems
      • String DP
      • Tree/Graph DP
      • Optimization Problems
      • Combinatorial DP
    • DFS
      • Graph Traversal
      • Path Finding
      • Tree Traversal
      • Backtracking
      • Topological Sorting
      • Traversal Order
      • Dynamic Programming with DFS
      • Connected Components
    • BFS
      • Graph
      • Tree
      • Matrix
      • String
      • Others
    • Two points
      • Array
      • String
      • Linked List
      • Sorting
      • Others
    • LinkedList
      • Basic Operations
      • Cycle Detection and Handling
      • Intersection and Union
      • Partitioning and Merging
      • Palindrome
      • Miscellaneous
    • Backtracking
    • Binary Search
    • Union Find
    • Trie
    • Sort
    • Heap
    • Randomness
    • Topological sort
    • Stack
    • HashTable
    • Sliding Window
  • Blind 75
    • Array
    • Binary
    • Dynamic Programming
    • Graph
    • Interval
    • LinkedList
    • Matrix
    • String
    • Tree
    • Heap
  • Companies
    • Apple
Powered by GitBook
On this page
  • 50. Longest Substring Without Repeating Characters
  • 51. Longest Repeating Character Replacement
  • 52. Minimum Window Substring
  • 53. Valid Anagram
  • 54. Group Anagrams
  • 55. Valid Parentheses
  • 56. Valid Palindrome
  • 57. Longest Palindromic Substring
  • 58. Palindromic Substrings
  • 59. Encode and Decode Strings (Leetcode Premium)
  1. Blind 75

String

50. Longest Substring Without Repeating Characters

  1. The problem "Longest Substring Without Repeating Characters" can be found on LeetCode: https://leetcode.com/problems/longest-substring-without-repeating-characters/

  2. Here is an optimized Java code for finding the length of the longest substring without repeating characters:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int maxLength = 0;
        int[] prevIndices = new int[256];
        Arrays.fill(prevIndices, -1);
        
        int start = 0;
        for (int end = 0; end < n; end++) {
            char c = s.charAt(end);
            if (prevIndices[c] >= start) {
                start = prevIndices[c] + 1;
            }
            prevIndices[c] = end;
            maxLength = Math.max(maxLength, end - start + 1);
        }
        
        return maxLength;
    }
}
  1. Algorithm and approach:

  • We will use the sliding window technique to solve this problem. The idea is to maintain a sliding window containing all the characters of the substring without repetition.

  • We will use two pointers, start and end, to define the current sliding window. Initially, both pointers will be at position 0.

  • Then, we will iterate over the string s, and for each character c at index end, we will check whether it has occurred previously within the current sliding window. If it has, we need to update the start pointer to the next position after the duplicate occurrence of c. The reason for this is that we want to maintain a substring without repeating characters, and by moving the start pointer, we can exclude the characters that have occurred previously in the substring.

  • Additionally, for each character c, we will update the prevIndices array to keep track of the most recent occurrence of that character. Each element of the prevIndices array will store the index of the most recent occurrence of the corresponding character within the sliding window.

  • Finally, for each iteration, we will calculate the length of the current substring (which is end - start + 1) and update the maxLength variable if necessary.

  • After iterating over the entire string, we will obtain the length of the longest substring without repeating characters.

In an interview, you can break down the problem into small steps and explain each step clearly, showing your understanding of the problem and how to approach it. Make sure to emphasize the time complexity of the solution and explain why it is efficient.

  1. Similar problems: The algorithm described above can be used for the following similar problems:

  • Longest Substring with At Most Two Distinct Characters

  • Longest Substring with At Most K Distinct Characters

  • Longest Substring with At Most K Repeating Characters

  • Longest Substring with At Most K Unique Characters

  1. Similar problems with detailed Java code and descriptions:

  • Longest Substring with At Most Two Distinct Characters:

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int n = s.length();
        int maxLength = 0;
        int[] count = new int[256];
        int distinctCount = 0;

        int start = 0;
        for (int end = 0; end < n; end++) {
            char c = s.charAt(end);
            if (count[c] == 0) {
                distinctCount++;
            }
            count[c]++;

            while (distinctCount > 2) {
                char startChar = s.charAt(start);
                count[startChar]--;
                if (count[startChar] == 0) {
                    distinctCount--;
                }
                start++;
            }

            maxLength = Math.max(maxLength, end - start + 1);
        }

        return maxLength;
    }
}

Description: This problem is a variation of the original problem where we need to find the longest substring with at most two distinct characters. The approach is similar to the original problem, but we maintain a distinct count and use a sliding window to update the start pointer when the distinct count exceeds 2.

  • Longest Substring with At Most K Distinct Characters:

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int n = s.length();
        int maxLength = 0;
        int[] count = new int[256];
        int distinctCount = 0;

        int start = 0;
        for (int end = 0; end < n; end++) {
            char c = s.charAt(end);
            if (count[c] == 0) {
                distinctCount++;
            }
            count[c]++;

            while (distinctCount > k) {
                char startChar = s.charAt(start);
                count[startChar]--;
                if (count[startChar] == 0) {
                    distinctCount--;
                }
                start++;
            }

            maxLength = Math.max(maxLength, end - start + 1);
        }

        return maxLength;
    }
}

Description: This problem is a generalization of the previous problem, where we need to find the longest substring with at most k distinct characters. The approach is similar to the previous problem, but we use a variable k to keep track of the maximum distinct count.

  • Longest Substring with At Most K Repeating Characters:

class Solution {
    public int lengthOfLongestSubstringKRepeating(String s, int k) {
        int n = s.length();
        int maxLength = 0;

        for (int i = 0; i < n; i++) {
            int[] count = new int[256];
            int uniqueCount = 0;
            int validCount = 0;

            for (int j = i; j < n; j++) {
                char c = s.charAt(j);
                count[c]++;
                if (count[c] == 1) {
                    uniqueCount++;
                    validCount++;
                } else if (count[c] == k) {
                    validCount++;
                }

                if (uniqueCount == validCount) {
                    maxLength = Math.max(maxLength, j - i + 1);
                }
            }
        }

        return maxLength;
    }
}

Description: This problem requires finding the longest substring where each character occurs at most k times. Here, we iterate over each possible starting index and maintain a count of each character in the substring. We keep track of the count of unique characters and the count of characters that occur exactly k times. If the unique count is equal to the valid count, it means that all characters in the substring occur at most k times, so we update the maxLength accordingly.

  • Longest Substring with At Most K Unique Characters:

class Solution {
    public int lengthOfLongestSubstringKUnique(String s, int k) {
        int n = s.length();
        int maxLength = 0;
        int[] count = new int[256];
        int uniqueCount = 0;

        int start = 0;
        for (int end = 0; end < n; end++) {
            char c = s.charAt(end);
            if (count[c] == 0) {
                uniqueCount++;
            }
            count[c]++;

            while (uniqueCount > k) {
                char startChar = s.charAt(start);
                count[startChar]--;
                if (count[startChar] == 0) {
                    uniqueCount--;
                }
                start++;
            }

            maxLength = Math.max(maxLength, end - start + 1);
        }

        return maxLength;
    }
}

Description: This problem is a variation where we need to find the longest substring with at most k unique characters. The approach is similar to the original problem, but instead of distinct count, we use unique count to keep track of the number of unique characters in the sliding window.

51. Longest Repeating Character Replacement

  1. Problem Description: The problem "Longest Repeating Character Replacement" on LeetCode asks us to find the length of the longest substring in a given string, where we can replace at most k characters to make the substring have the same repeating character. The problem link on LeetCode is: https://leetcode.com/problems/longest-repeating-character-replacement/

  2. Optimized Java Code (with detailed comments):

public class Solution {
    public int characterReplacement(String s, int k) {
        int maxLength = 0; // to store the length of the longest substring
        int start = 0; // start index of the current window
        int maxCount = 0; // to keep track of the count of the most frequent character in the current window
        int[] charCounts = new int[26]; // to store character counts
        
        for (int end = 0; end < s.length(); end++) {
            int index = s.charAt(end) - 'A'; // converting the character to an index
            
            charCounts[index]++; // increment the count for the current character
            
            maxCount = Math.max(maxCount, charCounts[index]); // update the maxCount
            
            // calculate the length of the current window
            int windowLength = end - start + 1;
            
            // check if we need to replace more than k characters in the current window
            // if so, move the start of the window forward and decrement the count of the character at the start
            if (windowLength - maxCount > k) {
                charCounts[s.charAt(start) - 'A']--;
                start++;
            }
            
            maxLength = Math.max(maxLength, windowLength); // update the maxLength
        }
        
        return maxLength;
    }
}
  1. Algorithm Explanation: The algorithm uses a sliding window approach to find the length of the longest substring with the same repeating character. We maintain a window where we can replace at most k characters to make the substring have the same repeating character. The window start and end indices are iterated through the string. At each iteration, we update the counts of the characters in the window, keep track of the count of the most frequent character, and calculate the length of the window. If the window length minus the count of the most frequent character exceeds k, we move the window start forward and decrement the count of the character at the start. The maxLength stores the maximum length seen so far. Finally, we return the maxLength.

During an interview, it's important to first understand the problem statement and the constraints. Then, discuss possible approaches and their time and space complexities. For this problem, using a sliding window approach is a commonly used technique to solve string-related problems.

  1. Abstracting Similar Problems: The algorithm used for solving the "Longest Repeating Character Replacement" problem can be used to solve other problems that involve finding the length of the longest substring with a specified condition. These problems can include finding the longest substring with the same number of 0s and 1s, finding the longest substring with at most k distinct characters, finding the longest substring with at most k vowels, etc.

  2. Similar Problems (with detailed Java code and descriptions):

  • Longest Substring with At Most K Distinct Characters:

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int maxLength = 0;
        int start = 0;
        int distinctCount = 0;
        int[] charCounts = new int[256];
        
        for (int end = 0; end < s.length(); end++) {
            if (charCounts[s.charAt(end)] == 0) distinctCount++;
            charCounts[s.charAt(end)]++;
            
            while (distinctCount > k) {
                if (charCounts[s.charAt(start)] == 1) distinctCount--;
                charCounts[s.charAt(start)]--;
                start++;
            }
            
            maxLength = Math.max(maxLength, end - start + 1);
        }
        
        return maxLength;
    }
}

This problem is similar to "Longest Repeating Character Replacement", but instead of replacing characters, we need to find the maximum length of a substring with at most k distinct characters.

  • Longest Substring with At Most K Vowels:

public class Solution {
    public int maxVowels(String s, int k) {
        int maxLength = 0;
        int start = 0;
        int vowelCount = 0;
        
        for (int end = 0; end < s.length(); end++) {
            char c = s.charAt(end);
            if (isVowel(c)) vowelCount++;
            
            int windowLength = end - start + 1;
            
            if (windowLength > k) {
                char startChar = s.charAt(start);
                if (isVowel(startChar)) vowelCount--;
                start++;
            }
            
            maxLength = Math.max(maxLength, vowelCount);
        }
        
        return maxLength;
    }
    
    private boolean isVowel(char c) {
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }
}

This problem requires finding the maximum length of a substring with at most k vowels, where 'a', 'e', 'i', 'o', and 'u' are considered vowels.

These problems demonstrate how the sliding window approach can be adapted to different conditions and constraints to find the length of the longest substring.

52. Minimum Window Substring

  1. Problem Description and Problem Link: The problem is titled "Minimum Window Substring" on LeetCode. You can find the problem here: https://leetcode.com/problems/minimum-window-substring/

  2. Optimized Java Code for Minimum Window Substring:

import java.util.HashMap;
import java.util.Map;

class Solution {
    public String minWindow(String s, String t) {
        // Step 1: Create a frequency map for the characters in t
        Map<Character, Integer> targetFreqMap = new HashMap<>();
        for (char ch : t.toCharArray()) {
            targetFreqMap.put(ch, targetFreqMap.getOrDefault(ch, 0) + 1);
        }
        
        // Step 2: Create pointers for left and right end of the window
        int left = 0, right = 0;
        int minWindowSize = Integer.MAX_VALUE;
        int minWindowStart = 0;
        int requiredChars = targetFreqMap.size();
        
        // Step 3: Create a sliding window to find the minimum substring
        Map<Character, Integer> windowFreqMap = new HashMap<>();
        int formedChars = 0;
        
        while (right < s.length()) {
            char ch = s.charAt(right);
            
            // Add the character to the window frequency map
            windowFreqMap.put(ch, windowFreqMap.getOrDefault(ch, 0) + 1);
            
            // If the current character is one of the required characters and its frequency matches the target frequency,
            // increment the count of formed characters
            if (targetFreqMap.containsKey(ch) && targetFreqMap.get(ch).equals(windowFreqMap.get(ch))) {
                formedChars++;
            }
            
            // Check if the current window contains all the required characters
            while (left <= right && formedChars == requiredChars) {
                // Update the minimum window size and start position if a smaller window is found
                if (right - left + 1 < minWindowSize) {
                    minWindowSize = right - left + 1;
                    minWindowStart = left;
                }
                
                // Shrink the window from the left
                char leftChar = s.charAt(left);
                windowFreqMap.put(leftChar, windowFreqMap.get(leftChar) - 1);
                
                // If the left character is one of the required characters and its frequency becomes less than the target frequency,
                // decrement the count of formed characters
                if (targetFreqMap.containsKey(leftChar) && windowFreqMap.get(leftChar) < targetFreqMap.get(leftChar)) {
                    formedChars--;
                }
                
                left++; // Move the left pointer ahead
            }
            
            right++; // Move the right pointer ahead
        }
        
        // If no valid window is found, return an empty string
        if (minWindowSize == Integer.MAX_VALUE) {
            return "";
        }
        
        // Return the minimum substring
        return s.substring(minWindowStart, minWindowStart + minWindowSize);
    }
}
  1. Detailed Description of the Algorithm and Thinking Process during Interviews: The given problem can be solved using the sliding window technique. The steps to solve this problem are as follows:

  • Step 1: Create a frequency map (targetFreqMap) for the characters in the target string t. This map will keep track of the required characters and their frequencies.

  • Step 2: Initialize two pointers, left and right, which represent the left and right end of the window, respectively. Also, initialize minWindowSize to Integer.MAX_VALUE and minWindowStart to 0. requiredChars keep track of the required characters count.

  • Step 3: Create a sliding window with the help of the pointers left and right. Iterate through the string s using the right pointer.

    • Add the character at index right to the windowFreqMap to keep track of its frequency in the current window.

    • If the current character is one of the required characters and its frequency matches the target frequency, increment the count of formedChars.

    • Check if the current window contains all the required characters. If it does, enter a while loop.

      • Update the minWindowSize and minWindowStart if a smaller window is found.

      • Shrink the window from the left by moving the left pointer ahead.

      • If the left character is one of the required characters and its frequency becomes less than the target frequency, decrement the count of formedChars.

  • After completing the iteration, if no valid window is found, return an empty string. Otherwise, return the minimum substring as per the calculated minWindowStart and minWindowSize.

During an interview, when solving similar problems using the sliding window technique, it is important to:

  • Clearly define the problem requirements and constraints.

  • Identify the suitable data structures to keep track of the required information.

  • Initialize pointers and variables properly.

  • Use loops effectively to iterate and manipulate the sliding window.

  • Handle edge cases and return the expected result.

  1. Abstracted Problems using the Similar Algorithm: The sliding window technique used in the "Minimum Window Substring" problem can be used to solve various other problems. Some abstracted problems where this technique can be used include:

  • Longest Substring Without Repeating Characters

  • Subarrays with K Distinct Integers

  • Minimum Size Subarray Sum

  • Maximum Length of Subarray With Positive Product

  • Permutation in String

  • Find All Anagrams in a String

  1. Similar Problems with Detailed Java Code and Descriptions:

  • Longest Substring Without Repeating Characters Problem Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;
        int left = 0, right = 0;
        Set<Character> window = new HashSet<>();

        while (right < s.length()) {
            char ch = s.charAt(right);
            while (window.contains(ch)) {
                window.remove(s.charAt(left));
                left++;
            }
            window.add(ch);
            maxLen = Math.max(maxLen, right - left + 1);
            right++;
        }

        return maxLen;
    }
}
  • Subarrays with K Distinct Integers Problem Link: https://leetcode.com/problems/subarrays-with-k-different-integers/

class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
        return atMostK(nums, k) - atMostK(nums, k - 1);
    }
    
    private int atMostK(int[] nums, int k) {
        int left = 0, right = 0;
        int count = 0;
        Map<Integer, Integer> freqMap = new HashMap<>();
        
        while (right < nums.length) {
            freqMap.put(nums[right], freqMap.getOrDefault(nums[right], 0) + 1);
            right++;
            
            while (freqMap.size() > k) {
                freqMap.put(nums[left], freqMap.get(nums[left]) - 1);
                if (freqMap.get(nums[left]) == 0) {
                    freqMap.remove(nums[left]);
                }
                left++;
            }
            
            count += right - left;
        }
        
        return count;
    }
}
  • Minimum Size Subarray Sum Problem Link: https://leetcode.com/problems/minimum-size-subarray-sum/

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int minLen = Integer.MAX_VALUE;
        int left = 0, right = 0;
        int sum = 0;

        while (right < nums.length) {
            sum += nums[right];

            while (sum >= target) {
                minLen = Math.min(minLen, right - left + 1);
                sum -= nums[left];
                left++;
            }

            right++;
        }

        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }
}
  • Maximum Length of Subarray With Positive Product Problem Link: https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/

class Solution {
    public int getMaxLen(int[] nums) {
        int maxLen = 0;
        int left = 0, right = 0;
        int negativeCount = 0;
        int firstNegativeIndex = -1;
        
        while (right < nums.length) {
            if (nums[right] < 0) {
                negativeCount++;
                if (firstNegativeIndex == -1) {
                    firstNegativeIndex = right;
                }
            }
            
            if (negativeCount % 2 == 0) {
                maxLen = Math.max(maxLen, right - left + 1);
            } else {
                maxLen = Math.max(maxLen, right - firstNegativeIndex);
            }
            
            if (nums[right] == 0) {
                left = right + 1;
                negativeCount = 0;
                firstNegativeIndex = -1;
            }
            
            right++;
        }
        
        return maxLen;
    }
}
  • Permutation in String Problem Link: https://leetcode.com/problems/permutation-in-string/

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int[] targetFreqMap = new int[26];
        int[] windowFreqMap = new int[26];
        
        for (char ch : s1.toCharArray()) {
            targetFreqMap[ch - 'a']++;
        }
        
        int left = 0, right = 0;
        int requiredChars = s1.length();
        
        while (right < s2.length()) {
            char ch = s2.charAt(right);
            
            if (targetFreqMap[ch - 'a'] > 0) {
                windowFreqMap[ch - 'a']++;
                if (windowFreqMap[ch - 'a'] <= targetFreqMap[ch - 'a']) {
                    requiredChars--;
                }
            }
            
            if (requiredChars == 0) {
                return true;
            }
            
            if (right - left + 1 >= s1.length()) {
                char leftChar = s2.charAt(left);
                
                if (targetFreqMap[leftChar - 'a'] > 0) {
                    windowFreqMap[leftChar - 'a']--;
                    if (windowFreqMap[leftChar - 'a'] < targetFreqMap[leftChar - 'a']) {
                        requiredChars++;
                    }
                }
                
                left++;
            }
            
            right++;
        }
        
        return false;
    }
}
  • Find All Anagrams in a String Problem Link: https://leetcode.com/problems/find-all-anagrams-in-a-string/

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        
        if (s.length() < p.length()) {
            return result;
        }
        
        int[] targetFreqMap = new int[26];
        int[] windowFreqMap = new int[26];
        
        for (char ch : p.toCharArray()) {
            targetFreqMap[ch - 'a']++;
        }
        
        int left = 0, right = 0;
        int requiredChars = p.length();
        
        while (right < s.length()) {
            char ch = s.charAt(right);
            
            if (targetFreqMap[ch - 'a'] > 0) {
                windowFreqMap[ch - 'a']++;
                if (windowFreqMap[ch - 'a'] <= targetFreqMap[ch - 'a']) {
                    requiredChars--;
                }
            }
            
            if (requiredChars == 0) {
                result.add(left);
            }
            
            if (right - left + 1 >= p.length()) {
                char leftChar = s.charAt(left);
                
                if (targetFreqMap[leftChar - 'a'] > 0) {
                    windowFreqMap[leftChar - 'a']--;
                    if (windowFreqMap[leftChar - 'a'] < targetFreqMap[leftChar - 'a']) {
                        requiredChars++;
                    }
                }
                
                left++;
            }
            
            right++;
        }
        
        return result;
    }
}

These are some similar problems that can be solved using the sliding window technique.

53. Valid Anagram

  1. Problem Description and Link: The problem "Valid Anagram" on LeetCode asks us to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. The problem can be found at the following link: https://leetcode.com/problems/valid-anagram/

  2. Java Code for Valid Anagram:

class Solution {
    public boolean isAnagram(String s, String t) {
        // Check if the lengths of the strings are equal
        if (s.length() != t.length())
            return false;
        
        // Initialize an array to count the occurrences of each character
        int[] count = new int[26];
        
        // Iterate over the first string and increment the count for each character
        for (int i = 0; i < s.length(); i++)
            count[s.charAt(i) - 'a']++;
        
        // Iterate over the second string and decrement the count for each character
        for (int i = 0; i < t.length(); i++)
            count[t.charAt(i) - 'a']--;
        
        // If any count is not 0, the strings are not anagrams
        for (int i = 0; i < 26; i++) {
            if (count[i] != 0)
                return false;
        }
        
        // If all counts are 0, the strings are anagrams
        return true;
    }
}
  1. Algorithm and Interview Approach: The algorithm to solve this problem is quite simple and efficient. We first check if the lengths of the strings are equal since anagrams must have the same number of characters. Then we initialize an array of size 26 to count the occurrences of each character in the first string. We iterate over the first string, and for each character, we increment the count in the array. Next, we iterate over the second string and, for each character, we decrement its count in the array. Finally, we check if all counts in the array are 0. If they are, the strings are anagrams.

During an interview, it is important to discuss the approach before jumping into coding. The interviewer may ask you to explain the time and space complexity of the algorithm. For this approach, the time complexity is O(n) since we iterate over the strings once, where n is the length of the strings. The space complexity is O(1) since the array has a fixed size of 26.

  1. Similar Algorithm Applications: This algorithm can be used to solve various other problems related to anagrams or character manipulation. Some examples include:

  • Group Anagrams: Given an array of strings, group them based on whether they are anagrams of each other or not.

  • Find All Anagrams in a String: Given a string and a pattern, find all anagrams of the pattern within the string.

  1. Similar Problems with Java Code and Descriptions:

  • Problem: Group Anagrams

    • Description: Given an array of strings, group them based on whether they are anagrams of each other or not.

    • LeetCode Link: https://leetcode.com/problems/group-anagrams/

    • Java Code:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0)
            return new ArrayList<>();
        
        Map<String, List<String>> anagramGroups = new HashMap<>();
        
        for (String str : strs) {
            char[] charArr = str.toCharArray();
            Arrays.sort(charArr);
            String sortedStr = String.valueOf(charArr);
            
            if (!anagramGroups.containsKey(sortedStr))
                anagramGroups.put(sortedStr, new ArrayList<>());
            
            anagramGroups.get(sortedStr).add(str);
        }
        
        return new ArrayList<>(anagramGroups.values());
    }
}
  • Problem: Find All Anagrams in a String

    • Description: Given a string and a pattern, find all anagrams of the pattern within the string.

    • LeetCode Link: https://leetcode.com/problems/find-all-anagrams-in-a-string/

    • Java Code:

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        if (s.length() < p.length())
            return result;
        
        int[] patternCount = new int[26];
        int[] windowCount = new int[26];
        
        for (char ch : p.toCharArray())
            patternCount[ch - 'a']++;
        
        for (int i = 0; i < p.length(); i++)
            windowCount[s.charAt(i) - 'a']++;
        
        if (Arrays.equals(patternCount, windowCount))
            result.add(0);
        
        for (int i = p.length(); i < s.length(); i++) {
            windowCount[s.charAt(i) - 'a']++;
            windowCount[s.charAt(i - p.length()) - 'a']--;
            
            if (Arrays.equals(patternCount, windowCount))
                result.add(i - p.length() + 1);
        }
        
        return result;
    }
}

These are just a few examples of problems that can be solved using a similar approach to check for anagrams or manipulate characters.

54. Group Anagrams

  1. Problem Description:

The problem "Group Anagrams" on LeetCode can be found at the following link:

Given an array of strings, you need to group the strings by anagrams and return their grouped representation.

For example, given ["eat", "tea", "tan", "ate", "nat", "bat"], we should group them as [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].

  1. Optimized Java Code:

Here's the optimized Java code for the "Group Anagrams" problem with detailed comments:

import java.util.*;

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        // Create a map to store the groups of anagrams
        Map<String, List<String>> map = new HashMap<>();
        
        // Iterate over each string in the input array
        for (String str : strs) {
            // Convert the string to a character array and sort it
            char[] arr = str.toCharArray();
            Arrays.sort(arr);
            
            // Convert the sorted character array back to a string
            String sortedStr = String.valueOf(arr);
            
            // If the sorted string does not exist in the map, add it as a new key with an empty list
            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            
            // Add the original string to the list associated with the sorted string key
            map.get(sortedStr).add(str);
        }
        
        // Return the grouped anagrams as a list of lists
        return new ArrayList<>(map.values());
    }
}
  1. Algorithm Explanation:

The algorithm follows the following steps:

  • Create a map to store the groups of anagrams, where the keys are the sorted strings and values are lists of anagrams.

  • Iterate over each string in the input array.

  • Convert the string to a character array and sort it.

  • Convert the sorted character array back to a string.

  • If the sorted string does not exist in the map, add it as a new key with an empty list.

  • Add the original string to the list associated with the sorted string key.

  • Finally, return the grouped anagrams as a list of lists.

During the interview process, it is important to understand the problem requirements and constraints and think about possible solutions. The key insight for this problem is to recognize that two strings are anagrams if and only if they have the same sorted string representation. By utilizing this property, we can efficiently group the anagrams together.

  1. Similar Problem Abstraction:

The algorithm used for grouping anagrams can be abstracted to solve problems that require grouping elements based on their properties or characteristics. Some examples include:

  • Grouping strings based on their lengths

  • Grouping numbers based on their parity (even or odd)

  • Grouping words based on their characters (e.g., vowels, consonants)

  1. Similar Problems:

Here are some similar problems with detailed Java code and explanations:

import java.util.*;

public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        Map<String, List<String>> map = new HashMap<>();
        
        for (String str : strings) {
            // Calculate the shifted string representation by finding the offset
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < str.length(); i++) {
                int offset = str.charAt(i) - str.charAt(i - 1);
                if (offset < 0)
                    offset += 26;
                sb.append(offset).append(',');
            }
            
            String shiftedStr = sb.toString();
            
            if (!map.containsKey(shiftedStr)) {
                map.put(shiftedStr, new ArrayList<>());
            }
            
            map.get(shiftedStr).add(str);
        }
        
        return new ArrayList<>(map.values());
    }
}
import java.util.*;

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        
        for (String str : strs) {
            char[] arr = str.toCharArray();
            Arrays.sort(arr);
            String sortedStr = String.valueOf(arr);
            
            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            
            map.get(sortedStr).add(str);
        }
        
        return new ArrayList<>(map.values());
    }
}

These problems use the same underlying algorithm of grouping elements based on some property or characteristic. By understanding the core concept, you can easily adapt the solution to solve similar problems in different contexts.

55. Valid Parentheses

Sure, I can help you with that!

  1. Problem Description: The problem is known as "Valid Parentheses". Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:

    • Open brackets must be closed by the same type of brackets.

    • Open brackets must be closed in the correct order.

  2. Optimized Java Code:

import java.util.Stack;

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        for(char c : s.toCharArray()){
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            } else if(c == ')' && !stack.isEmpty() && stack.peek() == '('){
                stack.pop();
            } else if(c == '}' && !stack.isEmpty() && stack.peek() == '{'){
                stack.pop();
            } else if(c == ']' && !stack.isEmpty() && stack.peek() == '['){
                stack.pop();
            } else{
                return false;
            }
        }
        
        return stack.isEmpty();
    }
}
  1. Algorithm Explanation and Interview Process: In this problem, we can use a stack to help us check if the parentheses are valid or not. We iterate over the string character by character.

    • If we encounter an opening parenthesis, we push it to the stack.

    • If we encounter a closing parenthesis, we check if the stack is empty (indicating an invalid string) or the top of the stack does not match the closing parenthesis (also indicating an invalid string). If either of these conditions is true, we return false. Otherwise, we pop the top element from the stack.

    After iterating over the whole string, if the stack is empty, it means all opening parentheses have been matched successfully, and the string is valid. Otherwise, there are remaining opening parentheses in the stack, indicating an invalid string.

    During an interview, it is important to discuss and clarify the requirements of the problem with the interviewer. Then, analyze the problem and come up with potential approaches. In this case, the stack-based approach is a commonly used approach for parentheses-related problems.

  2. Similar Algorithm Applications: The algorithm used to solve the "Valid Parentheses" problem can be applied to various similar problems. This algorithm is commonly used to validate expressions with balanced parentheses. Some examples are:

    • Checking the validity of expressions with parentheses, curly braces, and square brackets.

    • Validating HTML or XML tags.

    • Checking the validity of mathematical expressions.

  3. Similar Problems with Detailed Java Code and Descriptions:

      • Problem Description: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

      • Problem Description: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

      • Problem Description: Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

      • Problem Description: Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Please note that these are just a few examples, and there are many more related problems that can be solved using similar approaches.

56. Valid Palindrome

  1. Problem Description: The problem "Valid Palindrome" on LeetCode (https://leetcode.com/problems/valid-palindrome/) requires determining whether a given string is a valid palindrome. A palindrome is a string that reads the same forwards and backwards, ignoring any non-alphanumeric characters.

  2. Optimized Java Code for "Valid Palindrome" with Detailed Comments:

public class Solution {
    public boolean isPalindrome(String s) {
        // Convert the string to lowercase to ignore case sensitivity
        s = s.toLowerCase();
        
        // Initialize two pointers, left and right, to check characters from both ends of the string
        int left = 0;
        int right = s.length() - 1;
        
        while (left < right) {
            // Skip non-alphanumeric characters from the left pointer
            while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
                left++;
            }
            
            // Skip non-alphanumeric characters from the right pointer
            while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
                right--;
            }
            
            // Compare the characters at the left and right pointers
            if (s.charAt(left) != s.charAt(right)) {
                return false; // The string is not a palindrome
            }
            
            // Move the pointers towards the center
            left++;
            right--;
        }
        
        return true; // The string is a palindrome
    }
}
  1. Algorithm Explanation and Interview Approach: The approach to solve this problem is to use two pointers, starting from both ends of the string. We skip any non-alphanumeric characters and compare the characters at the two pointers. If they are not equal, then the string is not a palindrome.

During an interview, you can explain the algorithm in the following steps:

  • Convert the string to lowercase to ignore case sensitivity.

  • Initialize two pointers, left and right, to start from the beginning and end of the string, respectively.

  • Use a while loop to iterate until the left pointer is less than the right pointer.

  • Inside the loop, skip any non-alphanumeric characters by moving the left and right pointers accordingly.

  • Compare the characters at the left and right pointers. If they are not equal, then the string is not a palindrome, and we return false.

  • After the loop ends, if we haven't found any inequality, then the string is a palindrome, and we return true.

  1. Abstracting the Similar Algorithm: The algorithm to check whether a given string is a valid palindrome can be abstracted to solve similar problems involving comparing characters from both ends of a string or list.

  2. Similar Problems: Here is a list of similar problems with their detailed Java code and descriptions:

  • Problem: Valid Palindrome II

    • Link: https://leetcode.com/problems/valid-palindrome-ii/

    • Description: Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

    public class Solution {
        public boolean validPalindrome(String s) {
            // Use two pointers to check characters from both ends of the string
            int left = 0;
            int right = s.length() - 1;
            
            while (left < right) {
                // If characters are not equal, try skipping either left or right character
                if (s.charAt(left) != s.charAt(right)) {
                    return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
                }
    
                // Move the pointers towards the center
                left++;
                right--;
            }
            
            return true; // The string is already a palindrome
        }
        
        private boolean isPalindrome(String s, int left, int right) {
            while (left < right) {
                if (s.charAt(left) != s.charAt(right)) {
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
    }
  • Problem: Longest Palindromic Substring

    • Link: https://leetcode.com/problems/longest-palindromic-substring/

    • Description: Given a string s, find the longest palindromic substring in s.

    public class Solution {
        public String longestPalindrome(String s) {
            if (s == null || s.length() == 0) {
                return "";
            }
            
            String longestPalindrome = "";
            
            for (int i = 0; i < s.length(); i++) {
                String oddPalindrome = checkPalindrome(s, i, i);
                String evenPalindrome = checkPalindrome(s, i, i + 1);
                
                if (oddPalindrome.length() > longestPalindrome.length()) {
                    longestPalindrome = oddPalindrome;
                }
                
                if (evenPalindrome.length() > longestPalindrome.length()) {
                    longestPalindrome = evenPalindrome;
                }
            }
            
            return longestPalindrome;
        }
        
        private String checkPalindrome(String s, int left, int right) {
            while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            
            return s.substring(left + 1, right);
        }
    }

Note: These are just a few examples, and there are many other problems that can utilize a similar algorithm.

57. Longest Palindromic Substring

  1. Problem Description: You are given a string s. You need to find the longest palindromic substring in s.

Problem Link: https://leetcode.com/problems/longest-palindromic-substring/

  1. Optimized Java Code: Here's the optimized Java code for the "Longest Palindromic Substring" problem, along with detailed comments:

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return s; // Base case: Return the input string if it's null or has length less than 2
        }
        
        int n = s.length();
        int start = 0;
        int maxLength = 1;
        boolean[][] dp = new boolean[n][n];
        
        // Initialize the diagonal elements as true (single characters are palindrome)
        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
        }
        
        // Check for palindromic substring of length 2
        for (int i = 0; i < n - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                dp[i][i + 1] = true;
                start = i;
                maxLength = 2;
            }
        }
        
        // Check for palindromic substrings of length greater than 2
        for (int len = 3; len <= n; len++) {
            for (int i = 0; i < n - len + 1; i++) {
                int j = i + len - 1;
                if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
                    dp[i][j] = true;
                    start = i;
                    maxLength = len;
                }
            }
        }
        
        return s.substring(start, start + maxLength);
    }
}
  1. Algorithm Description: The optimized approach to find the longest palindromic substring is to use dynamic programming. We can use a 2D boolean array dp where dp[i][j] represents whether the substring from index i to index j is a palindrome or not. The algorithm involves the following steps:

  • Initialize the diagonal elements (dp[i][i]) as true since single characters are considered palindromes.

  • Check for palindromic substrings of length 2 and update the dp matrix accordingly.

  • Check for palindromic substrings of length greater than 2 in a bottom-up manner. If the characters at indices i and j are equal and the substring between i+1 and j-1 is also a palindrome (dp[i+1][j-1] = true), then the substring from i to j is a palindrome. Update the dp matrix, start index, and maxLength accordingly.

  • Finally, return the substring from the start index to start index + maxLength.

During the interview process, it's important to discuss the logic of the dynamic programming solution and explain the steps involved. Talk about the time complexity and space complexity of the algorithm (which is O(n^2)), and why it is an optimized solution for the problem.

  1. Similar Problems: The algorithm to find the longest palindromic substring can be applied to solve variations of the problem, such as:

  • Longest Palindromic Subsequence

  • Palindrome Partitioning

  • Longest Palindromic Subarray

  1. Similar Problems with Java Code: a) Longest Palindromic Subsequence: Problem Link: https://leetcode.com/problems/longest-palindromic-subsequence/

class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1; // Single characters are considered palindrome subsequence of length 1
        }
        
        for (int len = 2; len <= n; len++) {
            for (int i = 0; i < n - len + 1; i++) {
                int j = i + len - 1;
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1] + 2; // characters at indices i and j are equal
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); // characters at indices i and j are not equal
                }
            }
        }
        
        return dp[0][n - 1];
    }
}

b) Palindrome Partitioning: Problem Link: https://leetcode.com/problems/palindrome-partitioning/

class Solution {
    List<List<String>> result = new ArrayList<>();
    
    public List<List<String>> partition(String s) {
        backtrack(s, new ArrayList<>(), 0);
        return result;
    }
    
    private void backtrack(String s, List<String> current, int start) {
        if (start == s.length()) {
            result.add(new ArrayList<>(current));
            return;
        }
        
        for (int end = start; end < s.length(); end++) {
            if (isPalindrome(s, start, end)) {
                current.add(s.substring(start, end + 1));
                backtrack(s, current, end + 1);
                current.remove(current.size() - 1);
            }
        }
    }
    
    private boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

c) Longest Palindromic Subarray: Problem Link: https://leetcode.com/problems/longest-palindromic-subarray/

class Solution {
    public int longestPalindromeSubarray(int[] nums) {
        int n = nums.length;
        int[][] dp = new int[n][n];
        int maxLength = 1;
        
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1; // Single elements are palindrome subarrays of length 1
        }
        
        for (int len = 2; len <= n; len++) {
            for (int i = 0; i < n - len + 1; i++) {
                int j = i + len - 1;
                if (nums[i] == nums[j] && (len == 2 || dp[i + 1][j - 1] == 1)) {
                    dp[i][j] = 1;
                    maxLength = len;
                }
            }
        }
        
        return maxLength;
    }
}

In all these similar problems, the core logic is based on finding and utilizing palindromic properties of substrings or subarrays. You can discuss the similarities and differences between these problems and the Longest Palindromic Substring problem during the interview process.

58. Palindromic Substrings

Sure! Here's the information you requested:

  1. Problem Description: The problem Palindromic Substrings is available on LeetCode. You can find the problem statement and test cases at the following link: https://leetcode.com/problems/palindromic-substrings/

  2. Optimized Java Code: Below is the optimized Java code for the Palindromic Substrings problem with detailed comments:

class Solution {
    public int countSubstrings(String s) {
        int count = 0;
        int n = s.length();
        
        // Matrix to store if substring from i to j is palindrome
        boolean[][] dp = new boolean[n][n];
        
        // All individual characters are palindromes
        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
            count++;
        }
        
        // Check for substrings of length 2
        for (int i = 0; i < n - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                dp[i][i + 1] = true;
                count++;
            }
        }
        
        // Check for substrings of length greater than 2
        for (int len = 3; len <= n; len++) {
            for (int i = 0; i <= n - len; i++) {
                int j = i + len - 1; // Ending index of substring
                
                // Check if substring is palindrome
                if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
                    dp[i][j] = true;
                    count++;
                }
            }
        }
        
        return count;
    }
}
  1. Algorithm Explanation: The algorithm uses a dynamic programming approach to solve the problem. It maintains a 2D matrix dp to store whether a substring from index i to j is a palindrome or not. Initially, all individual characters are treated as palindromes. Then, substrings of length 2 are checked, and if they are palindromes, the count is increased. Finally, substrings of length 3 or greater are checked using the previous results in the matrix dp. If a substring is found to be a palindrome, the count is increased. The algorithm returns the total count of palindromic substrings.

During an interview process, it's important to approach this problem by breaking it down into smaller subproblems. Understanding the concept of palindromic substrings and how they are constructed will help in understanding the solution. A dynamic programming approach is often a good way to tackle string-related problems, as it allows for efficient solutions by reusing previously calculated results.

  1. Similar Problem Abstractions:

  • Count the number of palindrome subsequences: A similar algorithm can be used to count the number of palindrome subsequences in a given string, where subsequences can skip characters but maintain the original order.

  • Longest Palindromic Subsequence: The algorithm can be modified to find the length of the longest palindromic subsequence in a string, instead of counting the number of palindromic substrings.

  1. Similar Problems with Java Code:

  • Longest Palindromic Substring: https://leetcode.com/problems/longest-palindromic-substring/

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        boolean[][] dp = new boolean[n][n];
        int start = 0;
        int maxLen = 1;

        // All individual characters are palindromes
        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
        }

        // Check for substrings of length 2
        for (int i = 0; i < n - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                dp[i][i + 1] = true;
                start = i;
                maxLen = 2;
            }
        }

        // Check for substrings of length greater than 2
        for (int len = 3; len <= n; len++) {
            for (int i = 0; i <= n - len; i++) {
                int j = i + len - 1; // Ending index of substring
                
                // Check if substring is palindrome
                if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
                    dp[i][j] = true;
                    start = i;
                    maxLen = len;
                }
            }
        }

        return s.substring(start, start + maxLen);
    }
}
  • Palindrome Partitioning: https://leetcode.com/problems/palindrome-partitioning/

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();

        partitionHelper(s, 0, new ArrayList<>(), result);

        return result;
    }

    private void partitionHelper(String s, int start, List<String> current, List<List<String>> result) {
        if (start >= s.length()) {
            result.add(new ArrayList<>(current));
            return;
        }

        for (int end = start; end < s.length(); end++) {
            if (isPalindrome(s, start, end)) {
                current.add(s.substring(start, end + 1));
                partitionHelper(s, end + 1, current, result);
                current.remove(current.size() - 1);
            }
        }
    }

    private boolean isPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

These are some similar problems that utilize similar concepts and can be solved using a similar approach to the Palindromic Substrings problem. Please note that the provided codes are for your reference and understanding.

59. Encode and Decode Strings (Leetcode Premium)

  1. Java Code for "Encode and Decode Strings" problem:

public class Codec {
    
    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();
        for (String str : strs) {
            sb.append(str.length()).append('/').append(str);
        }
        return sb.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> res = new ArrayList<>();
        int i = 0;
        while (i < s.length()) {
            int slashIndex = s.indexOf('/', i);
            int len = Integer.parseInt(s.substring(i, slashIndex));
            res.add(s.substring(slashIndex + 1, slashIndex + len + 1));
            i = slashIndex + len + 1;
        }
        return res;
    }
}
  1. Algorithm and Interview Thought Process: The encode() function concatenates the given list of strings by prefixing each string with its length followed by a forward slash ('/') separator. The resulting encoded string can be decoded back into the original list of strings using the decode() function.

During an interview, to think through this problem, you can follow these steps:

  • Understand the problem statement and ask clarifying questions if needed.

  • Analyze the requirements and constraints.

  • Visualize some sample inputs and outputs.

  • Consider possible approaches and algorithms to solve the problem.

  • Implement the solution and test it with various edge cases.

  • Discuss the time and space complexity of the solution.

  • Analyze the efficiency and possible optimizations.

  1. Similar Algorithm Applications: The algorithm used in the "Encode and Decode Strings" problem can be used in similar scenarios where we need to encode and decode a list of strings, preserving their order and allowing easy reconstruction.

Some abstract problems that can use a similar algorithm include:

  • Serialization and deserialization of objects containing string fields.

  • Encoding and decoding of message packets in networking protocols.

  • Compression and decompression of multiple strings as a single entity.

  1. Similar Problems:

public class Codec {
    Map<Integer, String> map = new HashMap<>();
    Random rand = new Random();
    int key = rand.nextInt(10000);

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        while (map.containsKey(key)) {
            key = rand.nextInt(10000);
        }
        map.put(key, longUrl);
        return "http://tinyurl.com/" + key;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        int key = Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""));
        return map.get(key);
    }
}

These are examples of similar problems that involve encoding and decoding strings in various scenarios. Note that the solutions provided here are simplified versions that highlight the core encoding and decoding logic. In real-world scenarios, additional considerations such as handling collisions, security, and distributed systems may be necessary.

PreviousMatrixNextTree

Last updated 1 year ago

: Given a list of strings, group them together if they can be shifted to each other. Two strings are shifted if the character positions are shifted by the same offset.

: Given a string array, group anagrams together. Two strings are anagrams if they contain the same characters but in a different order.

Problem Link:

Problem Description: The problem "Encode and Decode Strings" is a question from Leetcode Premium, and the link to the problem is:

Group Anagrams
Group Shifted Strings
Group Shifted Strings
Valid Parentheses
Generate Parentheses
Java Code and Description
Longest Valid Parentheses
Java Code and Description
Minimum Add to Make Parentheses Valid
Java Code and Description
Remove Invalid Parentheses
Java Code and Description
Encode and Decode Strings - Leetcode Premium
Encode and Decode TinyURL
Encode and Decode TinyURL - Design a URL shortener service