Longest Substring Without Repeating Characters

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

For example –

Example 1:

Input: “abcabcbb” Output: 3

The output string is “abc”, with a length of 3.

Example 2:

Input: “bbbbb” Output: 1

The longest substring in this example is “b”. Its length is 1.

Example 3:

Input: “pwwkew” Output: 3

The answer is “wke”. Its length is 3.

Length of Longest Substring without Repeating Characters

In this tutorial, I am going to discuss how we can solve this problem efficiently using a sliding window approach and it’s java code. At the end of this tutorial, I have mentioned the link of the video tutorial.

Programming Video Tutorials

Let’s first see the brute force approach to solve this problem. The simplest approach is to form all the possible substrings and track the length of the longest substring with unique characters.

The time complexity of this approach is O(n^3).

Longest Substring Without Repeating Characters using Sliding Window – Java Code

Let’s improve our previous solution. In this example, I am going to explain how to find the length of longest non-repeating substring using sliding window approach.

The idea here is to maintain a window of unique character. Each window has start and end index, based on that we know the window size.To check unique character in a window, i am using set data structure. Set does not allow duplicate values and also the lookup time is O(1).

Here are the following steps to solve this problem –

  • Declare two indexes i and j and initialize with zero. Variable i indicate index of the start window and j indicate end index.
  • Traverse a string and pick one character at a time.
  • First check, if a character exists in a set. If it doesn’t exist in a set then add them in a set and increment the count of j and the index of i remain as it is. Also, keep track of the length of a window.
  • If character exists in a set then remove the character from a set and increment the count of i until all the characters in a window is unique again.
  • Repeat this step until the string is traversed completely.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Find first non-repeating character in a string

Longest Substring without Repeat InterviewBit Solution

The same problem is present in InterviewBit. The approach is same which i have already explained above.

Sort characters by frequency

Valid Palindrome

Check if a String is subsequence of another string

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.