Shortest substring with all characters

You have been given a string 'S' which only consists of lowercase English-Alphabet letters.

Your task is to find the shortest(minimum length) substring of 'S' which contains all the characters of 'S' at least once. If there are many substrings with the shortest length, then find one which appears earlier in the string i.e. substring whose starting index is lowest.

For example-
If the given string is S = "abcba", then the possible substrings are "abc" and "cba". As "abc" starts with a lower index (i.e. 0, "cba" start with index 2), we will print "abc" as our shortest substring that contains all characters of 'S'.
Input Format:
The only line of input contains a string 'S' i.e. the given string.
Output Format:
The only line of output contains a string i.e. the shortest substring of 'S' which contains all the characters of 'S' at least once.

Note:

You are not required to print the expected output, it has already been taken care of. Just implement the function.
Constraints:
1 <= N <= 10^5
'S' only contains lowercase English-Alphabet letters.

Where 'S' is the given string and ‘N’ is the length of ‘S’.

Time Limit: 1 sec 
CodingNinjas
author
2y

Step 1 : Need to have 0 index in one variable and then use .split() for the rest in the next variable
Step 2 : Take a loop start with the smallest possible substrings, then go up.
Step 3 : To make a fun...read more

CodingNinjas
author
2y
Naïve Solution

The problem boils down to counting distinct characters that are present in the string and then finding the minimum length substring that contains this many distinct characters at least o...read more

CodingNinjas
author
2y
Two Pointers

The idea is to use two pointers technique with a sliding window of variable length. The current window will be our current processing substring.

  • If the count of distinct characters of the...read more
Add answer anonymously...
Codalien Technologies Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter