Skip to main content

Java Problem 03 | Find Longest Substring Without Repeating Characters

 Ever felt like you're repeating yourself? Well, strings shouldn’t either! ๐Ÿงต

In this coding challenge, your mission is to find the longest section of a given string where no character appears more than once. It sounds simple, but it’s a classic puzzle that makes you think about efficiency, memory, and clever iteration.

What you’ll practice:

  • Looping through strings in smart ways
  • Tracking characters you’ve already seen (hint: sets or maps are your friends!)
  • Sliding window technique—a super useful tool for many problems
  • Writing clean, fast code without nested loops if possible

Example to get you started:

  • "abcabccc" → "abc" (length 3)
  • "defggft" → "defg" (length 4)

Think about:

  • What if the string is empty?
  • Should case matter? (usually yes, unless stated otherwise)
  • How can you avoid starting over from scratch each time?

It’s a perfect problem to level up your Java skills and get comfortable with more advanced string manipulation. Give it a try—and may your substrings always be unique! ✨



import java.util.*;

public class LongestSubstring {
// Main method to test the solution
public static void main(String[] args) {
// Problem: Longest Substring Without Repeating Characters
// Given a string s, find the length of the
// longest substring without duplicate characters.
// Test case 1:
// Input: s = "defggft"
// Expected Output: 4
// Explanation: The longest substring without duplicates is "defg"
System.out.println(longestSubStringFinder("defggft"));
// Test case 2:
// Input: s = "abcabccc"
// Expected Output: 3 (substring "abc")
System.out.println(longestSubStringFinder("abcabccc"));
}
// Method to find the longest substring without repeating characters
static int longestSubStringFinder(String s) {
// HashSet to track characters in the current sliding window
HashSet<Character> hashSet = new HashSet<>();
// Variable to store the longest substring found
String longestSubstring = "";
// Left pointer/index of the sliding window
int index = 0;
// Iterate through each character in the string
for (int i = 0; i < s.length(); i++) {
// If current character is already in the HashSet (duplicate found)
if (!hashSet.isEmpty() && hashSet.contains(s.charAt(i))) {
// Update longestSubstring if current window is longer
if (longestSubstring.length() < hashSet.size()) {
longestSubstring = getSubstring(hashSet);
}
// Move left pointer to remove characters until duplicate is gone
// This shrinks the window from the left
while (hashSet.contains(s.charAt(i))) {
hashSet.remove(s.charAt(index));
index++; // Move left pointer rightwards
}
// Add the current character (now unique in the window)
hashSet.add(s.charAt(i));
}
// Current character is not in the HashSet (unique in current window)
else {
hashSet.add(s.charAt(i));
}
// Check again if current window is the longest
if (longestSubstring.length() < hashSet.size()) {
longestSubstring = getSubstring(hashSet);
}
}
// Output the longest substring found
System.out.println(longestSubstring);
// Return the length of the longest substring
return longestSubstring.length();
}
// Helper method to convert HashSet of characters to a String
static String getSubstring(HashSet<Character> s) {
// StringBuilder for efficient string construction
StringBuilder stringBuilder = new StringBuilder();
// Append each character from HashSet to StringBuilder
for (char c: s) {
stringBuilder.append(c);
}
// Return the constructed string
return stringBuilder.toString();
}
// Note about the algorithm:
// This implements a sliding window approach with two pointers:
// - index (left pointer)
// - i (right pointer, from the for loop)
// Time complexity: O(n) where n is string length
// Space complexity: O(min(n, m)) where m is character set size
// Limitation: The current implementation has an issue:
// The getSubstring method doesn't preserve character order from the original string.
// The substring "defg" might be returned as a different permutation.
// To fix this, we should store the actual substring or its indices instead of using HashSet.
}








Longest Substring Without Repeating Characters

Enter string:

5 Implementation Methods

1. HashSet (Basic Sliding Window)

public static int lengthOfLongestSubstring(String s) {
    Set set = new HashSet<>();
    int max = 0, left = 0;
    for (int right = 0; right < s.length(); right++) {
        while (set.contains(s.charAt(right))) {
            set.remove(s.charAt(left++));
        }
        set.add(s.charAt(right));
        max = Math.max(max, right - left + 1);
    }
    return max;
}

2. HashMap (Optimized)

public static int lengthOfLongestSubstring(String s) {
    Map map = new HashMap<>();
    int max = 0, left = 0;
    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);
        if (map.containsKey(c) && map.get(c) >= left) {
            left = map.get(c) + 1;
        }
        map.put(c, right);
        max = Math.max(max, right - left + 1);
    }
    return max;
}

3. Integer Array (Most Efficient)

public static int lengthOfLongestSubstring(String s) {
    int[] index = new int[128]; // ASCII
    Arrays.fill(index, -1);
    int max = 0, left = 0;
    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);
        if (index[c] >= left) {
            left = index[c] + 1;
        }
        index[c] = right;
        max = Math.max(max, right - left + 1);
    }
    return max;
}
Complexity Comparison:
  • HashSet: Time: O(n), Space: O(min(n, m))
  • HashMap: Time: O(n), Space: O(min(n, m))
  • Integer Array: Time: O(n), Space: O(1) [for ASCII]
Tags: #JavaCoding #StringProblems #SlidingWindow #UniqueCharacters #ProgrammingPractice #CodeChallenge #LearnJava Java, CodingProblem, StringManipulation, SlidingWindow, Algorithm, ProgrammingChallenge, LearnJava, CodingPractice, UniqueCharacters, TechInterview, CodeNewbie, SoftwareDevelopment, ProblemSolving

Comments

Popular posts from this blog

How to fix MOV files not playing on Windows 10 or 11

How to TEST KEYBOARDS on PC or Laptop

Apple CONFIRMS iPhone 17 Pro Max Camera Noise Bug - Fix Coming?