Find Longest Sub-string without any Repeating characters.
💻 coding

Find Longest Sub-string without any Repeating characters.

1 min read 208 words
1 min read
ShareWhatsAppPost on X
  • 1A substring is a contiguous sequence of characters within a string, distinct from a subsequence.
  • 2The longest substring without repeating characters can be found using a HashMap to track character indices.
  • 3The time complexity of the provided solution is O(n) and the space complexity is O(n) in the worst case.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A substring is a contiguous sequence of characters within a string, distinct from a subsequence."

Find Longest Sub-string without any Repeating characters.

A substring is a contiguous sequence of characters within a string. For instance, "the best of" is a substring of "It was the best of times". This is not to be confused with subsequence, which is a generalization of a substring. For example, "Itwastimes" is a subsequence of "It was the best of times", but not a substring.

Prefix and suffix are special cases of a substring. A prefix of a string {\displaystyle S} S is a substring of {\displaystyle S} S that occurs at the beginning of {\displaystyle S} S. A suffix of a string {\displaystyle S} S is a substring that occurs at the end of {\displaystyle S} S.

The list of all substrings of the string "apple" would be "apple", "appl", "pple", "app", "ppl", "ple", "ap", "pp", "pl", "le", "a", "p", "l", "e", "".

import java.util.HashMap;

public class LongestSubstringWithoutRepeatingCharacters {

	public static void main(String[] args) {
		String str = "abcabcbb";
		HashMap<Character,Integer> map = new HashMap<Character,Integer>();
		int maxLen = 0;
		for(int i=0;i<str.length();i++) {
			if(map.containsKey(str.charAt(i))) {
				if((i - map.get(str.charAt(i))) > maxLen) {
					maxLen = i - map.get(str.charAt(i));
				}
				map.put(str.charAt(i), i);
			}
			else
				map.put(str.charAt(i), i);
		}
		
		System.out.println(maxLen);

	}

}

Output :

3

Time Complexity of Above solution is O(n) while space complexity is O(n) in the worst case.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 20 July 2018 · 1 min read · 208 words

Part of AskGif Blog · coding

You might also like

Find Longest Sub-string without any Repeating characters. | AskGif Blog