Skip to main content
3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Problem Statement

Given a string s, find the length of the longest substring without repeating characters.

Examples

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.

Difficulty

Medium

Constraints

  • 0 ≤ s.length ≤ 5 * 10⁴
  • s consists of English letters, digits, symbols and spaces.

Solution 1: Sliding Window (Using Two pointers + Hash Table)

Approach:

  1. Initialize an empty Set to store characters of the current window.
  2. Use two pointers i and j to represent the window. j is the leading pointer, and i is the trailing pointer.
  3. Iterate through the string with j. If the character s[j] is already in the set, it means we have a duplicate.
  4. Continuously remove s[i] from the set and increment i until s[j] is no longer in the set.
  5. Add s[j] to the set and update the maximum length ans = max(ans, j - i + 1).

Java


class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set st = new HashSet<>();
        int ans = 0;
        for (int i = 0, j = 0; j < s.length(); ++j) {
            char c = s.charAt(j);
            while (st.contains(c)) {
                st.remove(s.charAt(i++));
            }
            st.add(c);
            ans = Math.max(ans, j - i + 1);
        }
        return ans;
    }
}

C++


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_set st;
        int ans = 0;
        for (int i = 0, j = 0; j < s.size(); ++j) {
            while (st.count(s[j])) {
                st.erase(s[i++]);
            }
            st.insert(s[j]);
            ans = max(ans, j - i + 1);
        }
        return ans;
    }
};

Python


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        st = set()
        i = ans = 0
        for j, c in enumerate(s):
            while c in st:
                st.remove(s[i])
                i += 1
            st.add(c)
            ans = max(ans, j - i + 1)
        return ans

Complexity

Time: O(n) where n is the length of the string.

Space: O(k) where k is the number of unique characters in the string.

← All Problems

Comments

Popular posts from this blog

128. Longest Consecutive Sequence - Solution 128. Longest Consecutive Sequence Problem Statement 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. Examples 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 Difficulty Hard Solution 1: Sorting Approach: Sort the array and traverse it. Skip duplicates. If the current number is prev + 1 , increment the count; otherwise, reset it. Keep track of the maximum count. Java class Solution { public int longestConsecutive(int[] nums) { if (nums.length == 0) return 0; Arrays.sort(nums); int ans = 1, t = 1; for (int i = 1; i C++ class Solution { publi...
1. Two Sum Problem Statement Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target . You may assume that each input has exactly one solution, and you may not use the same element twice. You can return the answer in any order. Examples Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Difficulty Easy Constraints 2 ≤ nums.length ≤ 10⁴ -10⁹ ≤ nums[i] ≤ 10⁹ -10⁹ ≤ target ≤ 10⁹ Only one valid answer exists Solution 1: Using Hash Map Approach: Use a hash map to store value → index Iterate through array Check complement (target - current value) If found, return answer Else store value Java class Solution { public int[] twoSum(int[] nums, int target) {...
133. Clone Graph - Solution 133. Clone Graph Problem Statement Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a value ( int ) and a list ( List[Node] ) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val = 1 , the second node with val = 2 , and so on. The graph is represented in the test case using an adjacency list. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with val = 1 . You must return the copy of the given node as a reference to the cloned graph. Examples Example 1: Input: a...