LeetCode – Longest Substring Without Repeating Characters (Java)

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Java Solution 1

The first solution is like the problem of "determine if a string has all unique characters" in CC 150. We can use a flag array to track the existing characters for the longest substring without repeating characters.

public int lengthOfLongestSubstring(String s) {
        if(s==null)
            return 0;
	boolean[] flag = new boolean[256];
 
	int result = 0;
	int start = 0;
	char[] arr = s.toCharArray();
 
	for (int i = 0; i < arr.length; i++) {
		char current = arr[i];
		if (flag[current]) {
			result = Math.max(result, i - start);
			// the loop update the new start point
			// and reset flag array
			// for example, abccab, when it comes to 2nd c,
			// it update start from 0 to 3, reset flag for a,b
			for (int k = start; k < i; k++) {
				if (arr[k] == current) {
					start = k + 1; 
					break;
				}
				flag[arr[k]] = false;
			}
		} else {
			flag[current] = true;
		}
	}
 
	result = Math.max(arr.length - start, result);
 
	return result;
}

Java Solution 2

This solution is from Tia. It is easier to understand than the first solution.

The basic idea is using a hash table to track existing characters and their position. When a repeated character occurs, check from the previously repeated character. However, the time complexity is higher - O(n).

public static int lengthOfLongestSubstring(String s) {
        if(s==null)
            return 0;
	char[] arr = s.toCharArray();
	int pre = 0;
 
	HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 
	for (int i = 0; i < arr.length; i++) {
		if (!map.containsKey(arr[i])) {
			map.put(arr[i], i);
		} else {
			pre = Math.max(pre, map.size());
			i = map.get(arr[i]);
			map.clear();
		}
	}
 
	return Math.max(pre, map.size());
}

Java Solution 3

public int lengthOfLongestSubstring(String s) {
    if(s==null){
        return 0;
    }
 
    int max = 0;
 
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    int start=0;
 
    for(int i=0; i<s.length(); i++){
        char c = s.charAt(i);
        if(map.containsKey(c)){
            max = Math.max(max, map.size());    
            while(map.containsKey(c)){
                map.remove(s.charAt(start));
                start++;
            }
 
            map.put(c, i);
        }else{
            map.put(c, i);
        }
    }
 
    max = Math.max(max, map.size());  
 
    return max;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Milan

    //time : O(n) space : O(n)

    public class Solution {
    public int lengthOfLongestSubstring(String s) {
    int start = 0,max = 0,i =0;
    Map lookup = new HashMap();
    for (;i= start) {
    max=Math.max(max,i-start);
    start=lookup.get(ch)+1;
    }
    lookup.put(ch,i);
    }
    max=Math.max(max,i-start);
    return max;
    }
    }

  • jeevs

    public class longestsubstring {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in=new Scanner(System.in);
    ArrayList a=new ArrayList();
    String s=in.next();
    String temp=””;
    String target=””;
    for(int i=0;itarget.length())
    target=temp;
    a.clear();
    temp=””;
    }
    }
    System.out.print(target);
    }

  • Eugene Arnatovich

    Yep. That was my misunderstanding… Hope now it is better…

  • Larry Okeke

    simple solution

    import java.util.*;

    public class longest_substring{

    /*

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

    For example, the longest substring without repeating letters for "abcabcbb" is "abc",

    which the length is 3. For "bbbbb" the longest substring is "b",

    with the length of 1.

    */

    public static void main(String[] args){

    System.out.println("longest " +get_longest(args[0]));

    }

    public static int get_longest(String str){

    HashSet wordSet = new HashSet();

    int longest = 0;

    for(int i = 0; i < str.length(); i++){

    for(int j = i; j longest){

    longest = wordSet.size();

    }

    wordSet.clear();

    break;

    }

    }

    }

    return longest;

    }

    }

  • Larry Okeke

    Lol! Are you kidding?

  • Eugene Arnatovich

    Simplest solution:

    //Longest Substring Without Repeating Characters (Java)
    public int solution(String s) {
    Set set = new LinkedHashSet();
    for (char c : s.toCharArray()) {
    set.add(c);
    }
    return set.size();
    }

  • Adrian

    Following code is O(N) time complexity and constant space complexity O(1).

    public int LongestSubstringWithoutRepeatingCharacters(String src)
    {
    if (src == null || src.Length == 0)
    return 0;

    // v[j] stores i position of the src[i] character, where j = src[i]
    int[] v = new int[256];
    // Initialize visited state
    for (int i = 0; i < 256; ++i)
    v[i] = -1;

    v[src[0]] = 0;

    // start position of the longest string of non repeating characters
    int start = 0;
    // max length of string with non repeating characters so far
    int max_len = 1;

    for (int i = 1; i < src.Length; ++i)
    {
    if (v[src[i]] == -1)
    {
    v[src[i]] = i;
    ++max_len;
    }
    else
    {
    int cur_len = i - start;
    if (max_len < cur_len)
    max_len = cur_len;

    // move start of the substring with non repeating characters
    // after already visited(repeated) character
    start = v[src[i]] + 1;
    }
    }

    return max_len;
    }

  • Truong Khanh Nguyen
  • Ankit Shah

    Following works and it also prints the substring

  • CRH

    Why is the time complexity mentioned as n^3 for Java Solution 2 above? It should be O(n). The first loop is O(n) and in that main loop i is getting pushed back to an already visited location. So effectively we may end up looping through the whole loop 2n times. That still means O(n), then why n^3 is mentioned.

    Please help!

  • pm

    public class LCSWIthoutRepeating{
    public static void main(String args[]){
    String str = “aaaaapritikamehta”;
    LinkedHashMap hash = new LinkedHashMap();
    int maxLen =0;
    int max =0;
    int num =0;
    int arr[] = new int[26];
    for(int i =0;i<str.length();i++){
    char c = str.charAt(i);
    if(hash.get(c) == null){
    hash.put(c, i);
    max++;
    }else{
    maxLen = i – hash.get(c)max?maxLen:max);
    }

    }

  • southie

    O(n) solution with LinkedHashSet JAVA !

    public class LongestPalindromeWithoutRepChar {

    public static int lengthOfLongestSubstring(String s) {
    int maxCount=0;
    if(s.length() < 2) return s.length();
    Set hs = new LinkedHashSet();

    for(int i=0;i maxCount) maxCount = hs.size();
    Iterator itr = hs.iterator();
    Character curr = null;
    while(c!=curr)
    {
    curr = itr.next();
    itr.remove();
    }
    }
    }

    return maxCount;
    }
    }

  • Holden

    Why time complexity of second approach is O(n^3)?

  • NB****


    void LargestNonRepeatedSubStr() {
    string str = "abcabcbb";
    int max_length = 0;
    int i = 0;
    while (i < str.length()) {
    set check_set;
    int j = i;
    int length = 0;
    while (j < str.length()) {
    if (check_set.find(str[j]) != check_set.end()) {
    break;
    } else {
    check_set.insert(str[j]);
    length++;
    }
    j++;
    }
    check_set.clear();
    max_length = std::max(max_length, length);
    i++;
    }
    cout << "The max length is: " << max_length << "n";
    }

  • Sahil Singla

    It is required. Consider the case “dabcabcde”. If ‘map.get(arr[i]) < j' is not done then, for the iteration with "i=7" it would be computed that "d" has already contained in the HashMap and also the logic inside the "else" will fail and compute to give 'curr=7'.

  • dtReloaded

    List list = new ArrayList();

    for(int i=0 ; i<a.length();i++){

    if(!list.contains(a.charAt(i))){

    list.add(a.charAt(i));

    }

    else

    break;

    }

    System.out.println("The String Lengtht" +a.length());

  • Satish

    public static String uniqueCharSubstring(String str) {
    String result = “”;
    int len = str.length();
    HashMap map = new HashMap();
    char[] c = str.toCharArray();
    int right = 0, max = 0;
    for (int left = 0; left < len; left++) {
    while (right max) {
    max = right – left;
    result = str.substring(left, right + 1);
    }
    right++;
    }
    }
    return result;
    }

  • Vimukthi Weerasiri

    Thanks. Agree. Updated the code with some refactoring 🙂 Intention was to initialize it one prior to the rightPointer. Comments are welcome!

  • test

    second = -1 is pretty weird.

  • Vimukthi Weerasiri

    A simpler O(n) solution.

    public int lengthOfLongestSubstring(String s) {
    HashMap map = new HashMap();
    if (s == null || s.length() == 0) return 0;
    int first = 0, second = -1, answer = 0;
    while (first != s.length()) {
    Integer previousOccurrence = map.put(s.charAt(first), first);
    if (previousOccurrence != null) second = Math.max(second, previousOccurrence);
    answer = Math.max(answer, first – second);
    first++;
    }
    return answer;
    }

  • Edmond Hong

    I don’t think you need add the statement: ‘map.get(arr[i]) < j'

  • Sahil Singla

    I believe this is O(n):

    public static int lengthOfLongestSubstring(String s) {
    if(s==null)
    return 0;
    char[] arr = s.toCharArray();
    int pre = 0;
    HashMap map = new HashMap();
    int j = 0;
    int curr = 0;
    for (int i = 0; i < arr.length; i++) {
    if (!map.containsKey(arr[i]) || map.get(arr[i]) < j) {
    map.put(arr[i], i);
    curr++;
    } else {
    pre = Math.max(pre, curr);
    j = map.get(arr[i]) + 1;
    curr = i + 1 – j;
    map.put(arr[i], i);
    }
    }
    return Math.max(pre, curr);
    }

  • Adil qureshi

    can you explain why second one in On3 .. i cant get it … thanks

  • For the solution using the HashMap, I think the following line :
    i = map.get(arr[i]);
    should be changed to :
    i = map.get(arr[i])+1;
    Otherwise you will get an infinite loop ?

  • Parag Chaudhari
  • Mehmet

    What is the time and space complexity of first solution?

  • ryanlr

    No, it doesn’t. For example, given “abac”, when it meets the second “a”, aux should not be set to “a”, instead it should be set to “ba”.

  • Tiago

    I think the following works too:

    static public String nonRepeated(String input){

    char[] charAInput = input.toCharArray();
    String aux = “”;
    String resultSubStr = “”;

    if(input.length() == 1)
    return input;

    for(int i =0; i < charAInput.length; i++ ){

    if(!aux.contains("" + charAInput[i])){

    aux = aux.concat("" + charAInput[i]);

    }
    else
    aux = "" + charAInput[i];

    if(resultSubStr.length() < aux.length())
    resultSubStr = aux;
    }

    System.out.println(resultSubStr);

    return resultSubStr;

    }

  • ryanlr

    You solution is wrong. maxStart is not updated correctly.

  • ryanlr

    Your code is not right, for example, “aab”.

  • ryanlr

    Thanks. I think the problem is fixed now.

  • ryanlr

    Your code only compares the two consecutive characters, it can not handle case like “a”.

  • Arpit Pandey

    “bbabceabcdbb” fails with this string returns a wrong string

  • Tarun Singh

    I think Following is O(n) Solution 😀

    public static int lengthOfLongestSubstring(String s) {

    char[] arr = s.toCharArray();

    int pre = 0;

    int k=0;

    boolean flag = true;

    HashMap map = new HashMap();

    for (int i = 0; i pre)

    pre=l;

    k = map.get(arr[i]);

    map.put(arr[i],i);

    k++;

    }

    }

    if(flag) pre = arr.length;

    return pre;

    }

  • neckBeardThePirate

    how is solution two O(n^3)?

  • Zaga

    So I came up with an O(n) solution in python, please help me detect in what cases it can possibly fail

    #put test string here

    string = “eadsabcadcfef”

    indexOfSubsequence = 0

    tempIndexOfSubsequence = 0

    lenghtOfSubsequence = 0

    tempLenghtOfSubsequence = 0

    tableOfCharsIndex = [-1] * 26

    for i in xrange(0, len(string)):

    indexOfChar = ord(string[i]) – 97

    if tableOfCharsIndex[ indexOfChar ] == -1 or tableOfCharsIndex[ indexOfChar ] lenghtOfSubsequence :

    lenghtOfSubsequence = tempLenghtOfSubsequence

    indexOfSubsequence = tempIndexOfSubsequence

    else:

    if tempLenghtOfSubsequence > lenghtOfSubsequence :

    lenghtOfSubsequence = tempLenghtOfSubsequence

    indexOfSubsequence = tempIndexOfSubsequence

    tempIndexOfSubsequence = i

    tempLenghtOfSubsequence = 1

    tableOfCharsIndex[ indexOfChar ] = i

    print string[ indexOfSubsequence : indexOfSubsequence + lenghtOfSubsequence ]

    print lenghtOfSubsequence

  • Zy

    Hi Ryan,

    I like your site a lot, but I noticed that the recently-added social area on every post is blocking the sight.

    Hopefully this can be fixed and I can enjoy reading your site again.

  • Wally Osmond

    public static int getNoRepeatLen (String str) {

    int max=0,tLen=0;

    for(int i=1;i<str.length();i++) {

    if(str.charAt(i-1) == str.charAt(i)){

    max=Math.max(tLen+1,max);

    tLen=0;

    } else {

    tLen++;

    }

    }

    return Math.max(max,tLen);

    }

  • Wally Osmond

    Hey guys,

    Isn’t the best solution just a simple for loop with an if and some counters? Perhaps my solution is too simple and crashes or returns the results incorrectly somehow??? I tested it for the longest string and the beginning/end/middle and I believe it works.

    public static int getNoRepeatLen (String str) {

    int max=0,tLen=0;

    for(int i=1;i<str.length();i++) {

    if(str.charAt(i-1) == str.charAt(i)){

    max=Math.max(tLen+1,max);

    tLen=0;

    } else {

    tLen++;

    }

    }

    return Math.max(max,tLen);

    }

  • Jianwei Chen

    this is simpler.
    public static lls(String s) {
    HashMap map = new HashMap();

    int maxStart = 0;

    int pre = 0;

    for(int i = 0; i pre) {

    pre = map.size();

    maxStart = map.get(c);

    }

    }

    map.put(c, i);

    }

    return s.substring(maxStart, maxStart+pre);
    }

  • Krzysztof Rajda

    Proposed solution could be improved. You don’t need to clear the whole map and change i.

    private static String calculateFast(String text) {
    Map map = new HashMap();

    int maxStart = 0;
    int maxEnd = 1;
    int currentStart = 0;

    for (int i = 0; i maxEnd – maxStart) {
    maxStart = currentStart;
    maxEnd = i;
    }
    currentStart = firstOccurrenceIndex + 1;
    }
    map.put(c, i);
    }

    if (text.length() – currentStart > maxEnd – maxStart) {
    maxStart = currentStart;
    maxEnd = text.length();
    }

    return text.substring(maxStart, maxEnd);
    }

  • chitti

    this code handles:

    public String getLongestSubStringWithoutRepeatedChar (String str) {
    {
    List list = new ArrayList();
    String longestSoFar =””;
    int count = 0;
    int longestSize=0;

    //str.length()+1 for capturing longest string at the end.
    for (int i = 0; i < str.length()+1; i++) {
    if (i longestSize) {
    longestSize=count;
    longestSoFar = getLongestString(list);
    System.out.println(longestSoFar);
    }
    count=0;
    list.clear();

    }
    }

    return longestSoFar;
    }
    }

    private String getLongestString (List list) {
    StringBuilder sb = new StringBuilder();
    for (Character c : list) {
    sb.append(c);
    }
    return sb.toString();
    }

  • chitti

    corrected one:

    public String getLongestSubStringWithoutRepeatedChar (String str) {
    {
    List list = new ArrayList();
    String longestSoFar =””;
    int count = 0;
    int longestSize=0;

    for (int i = 0; i longestSize) {
    longestSize=count;
    longestSoFar = getLongestString(list);
    System.out.println(longestSoFar);
    }
    count=0;
    list.clear();

    }
    }
    return longestSoFar;
    }
    }

    private String getLongestString (List list) {
    StringBuilder sb = new StringBuilder();
    for (Character c : list) {
    sb.append(c);
    }
    return sb.toString();
    }

  • chitti

    Does not work for string “eadsabcadcfef”

  • Alex

    How about this O(n) solution? It’s easy to understand and allows for the retrieval of the longest substring as well:

    public static int lengthOfLongestSubstring(String word) {

    int start = 0;

    int end = 0;

    int maxStart = 0;

    int maxEnd = 0;

    int[] seen = new int[256];

    for (int i = 0; i < 256; i++) {

    seen[i] = -1;

    }

    for (int i = 0; i = start) {

    start = seen[c] + 1;

    }

    end++;

    seen[c] = i;

    if (end – start > maxEnd – maxStart) {

    maxEnd = end;

    maxStart = start;

    }

    }

    // Return word.substring(maxStart, maxEnd) for actual substring

    return maxEnd – maxStart;

    }

  • santhoshvai

    I am sorry.. i misunderstood LIS.. this http://ideone.com/hcLYgy should fix it

  • Jonathan Young

    abcadeftgh ==> bcadeftgh (this is the longest substring without repeating element, and its length is 9)

  • santhoshvai

    I found the mistake, see this http://ideone.com/WMXFOw

    the LIS for “abcadeftgh” is 7

  • Jonathan Young

    This doesn’t work if you pass “abcadeftgh” to your method. It should output 9 instead of 6

  • santhoshvai

    I have written a much simpler version than version 2 (python).. easier to understand. its here, http://ideone.com/BHJlvS

  • santhoshvai

    whats the need for ” i = h.get(target[i]); ” ? It should work without it

  • sudhansu jena

    Hi guys My solution simple and works fine.

    public String getLongestSubStringWithoutRepeatedChar(String str){

    ArrayList list=new ArrayList();

    String longestSoFar=””;

    int count=0;

    for(int i=0;i<str.length();i++){

    if(!list.contains(str.charAt(i))){

    list.add(str.charAt(i));

    }else{

    if(count<list.size()){

    count=list.size();

    longestSoFar=getLongestString(list);

    list.clear();

    }

    }

    }

    return longestSoFar;

    }

    private String getLongestString(ArrayList list) {

    StringBuilder sb=new StringBuilder();

    for(Character c:list){

    sb.append(c);

    }

    return sb.toString();

    }

  • Cheng Wang

    My solution but no idea why it is not correct:

    public class Solution {

    public int lengthOfLongestSubstring(String s) {

    // if the string is empty or has only one character

    if (s.length() < 2) return s.length();

    HashMap hashMap = new HashMap();

    int j = 0;

    int maxLen = 1;

    for (int i = 0; i < s.length(); i++) {

    if (!hashMap.containsKey(s.charAt(i))) {

    hashMap.put(s.charAt(i), i);

    } else {

    maxLen = Math.max(maxLen, i – j);

    j = hashMap.get(s.charAt(i)) + 1;

    hashMap.put(s.charAt(i), i);

    }

    }

    return Math.max(maxLen, s.length() – j);

    }

    }

  • Coder

    Solution 2 cannot pass the OJ because of the Time limit.

  • amit malik

    Updated Tia solution to

    1. Find all patterns with no repeating characters.

    2. Find the longest pattern and its size.

    public static void printPatternWithNoReaptingCharsInString(String s) {

    char[] arr = s.toCharArray();

    Map charMap = new HashMap();

    int size = 0;

    List uniquePatterns = new ArrayList();

    StringBuilder str = new StringBuilder();

    for (int i = 0; i < arr.length; i++) {

    if (!charMap.containsKey(arr[i])) {

    charMap.put(arr[i], i);

    } else {

    if (size <= charMap.size()) {

    size = charMap.size();

    if (str.length() <= size) {

    str.delete(0, str.length()).append(

    s.substring(i – size, i));

    uniquePatterns.add(str.toString());

    }

    }

    i = charMap.get(arr[i]);

    charMap.clear();

    }

    }

    System.out.println("Longest Pattern with no repeating characters:"

    + str.toString() + " with size " + size);

    System.out.println("There are in total " + uniquePatterns.size()

    + " patterns with no repeating characters.");

    }

    Below method call:

    printUniquePatterninString("abcdaaabcdaabcdebbpqrstuvaaa");

    will print:

    Longest Pattern with no repeating characters:bpqrstuva with size 9

    There are in total 6 patterns with no repeating characters.

  • play_boy

    Tia’s solution is good.
    I have the same solution but something different.
    The time : O(n)
    The space may be : O(n)
    and it can output the maxlength substring. (you need to delete the comment tag, and run it)
    like this:

    public static int lengthOfLongestSubstring(String s) {
    char[] arr = s.toCharArray();
    int maxlength = 0;
    int oldstart = 0;
    int newstart = 0;
    // int compare_times = 0; // compare times

    HashMap num = new HashMap(); // recode char and the char index
    HashMap map = new HashMap(); // recode index and the index of char

    for (int i = 0; i < arr.length; i++) {
    // compare_times++; //
    if (num.get(arr[i]) != null) {
    int end = num.get(arr[i]) + 1;
    for (int j = newstart; j < end; j++)
    { // compare times will less than s.length()
    num.remove(map.get(j));
    map.remove(j);
    }
    newstart = end;
    if (maxlength < num.size()) {
    maxlength = num.size();
    oldstart = newstart;
    }
    }
    num.put(arr[i], i);
    map.put(i, arr[i]);
    }
    if (maxlength < num.size()) {
    maxlength = num.size();
    oldstart = newstart;
    }
    // System.out.println("compare_times:" + compare_times); // output the compare times
    // System.out.println(s.substring(oldstart, oldstart + maxlength)); // output the longest substring
    return maxlength;
    }

  • neal

    this solution has time limited issue in leetcode.

  • ryanlr

    good solution, thanks.

  • ryanlr

    It’s the same.

  • lee

    string longestStr = string.Empty;

    int length = str.Length;

    int i = 0;

    Loop:

    string tempLongestStr = string.Empty;

    for (int j = i; j longestStr.Length)

    {

    longestStr = tempLongestStr;

    }

    i = i + tempLongestStr.IndexOf(temp) + 1;

    goto Loop;

    }

    else

    {

    tempLongestStr += temp;

    if (tempLongestStr.Length > longestStr.Length)

    {

    longestStr = tempLongestStr;

    }
    }

    }

    Console.WriteLine(longestStr);
    Console.ReadLine();

  • junmin

    public static int LongestSubStrWithUniqueChars(String s){
    if(s==null || s.isEmpty())
    return 0;

    char[] chars = s.toCharArray();

    int current = 0;//current pos in string
    int length = 0; //current longest substr length
    int pos = 0; //current longest substr starting pos

    for(current =0 ; current<s.length(); current++){
    pos = current;
    boolean[] found = new boolean[256];
    while(current<s.length() && !found[chars[current]]){
    found[chars[current]] = true;
    current++;
    }
    length = Math.max(length, current – pos);
    current = pos;
    }
    return length;
    }

  • tia

    Here is my solution with hash:


    public int solution(String s) {

    // IMPORTANT: Please reset any member data you declared, as

    // the same Solution instance will be reused for each test case.

    char[] target = s.toCharArray();

    int pre = 0;

    Hashtable h = new Hashtable();

    for(int i =0; i h.size() ? pre : h.size();

    i = h.get(target[i]);

    h.clear();
    }
    }
    return Math.max(pre, h.size());
    }