Shortest Substring with All Characters

Determine the shortest substring of the string S that includes every character from S at least once. If multiple shortest substrings exist, return the one that starts the earliest in S.

Input:

The input contains a single string 'S' consisting of only lowercase English letters.

Output:

Output the shortest substring of 'S' that contains all unique characters from 'S'.

Example:

Input:
"abcba"
Output:
"abc"
Explanation:

In the string S = "abcba", the substrings "abc" and "cba" both contain all characters of S. "abc" begins at index 0, earlier than "cba" which begins at index 2. Hence, the answer is "abc".

Constraints:

  • 1 <= N <= 10^5
  • S consists only of lowercase English letters.

Where S denotes the input string and N is its length.

Note: You do not need to print anything; implement the function as per the requirements.

AnswerBot
4mo

Find the shortest substring in a string that contains all unique characters.

  • Use a sliding window approach to find the shortest substring with all unique characters.

  • Keep track of the characters in the ...read more

Help your peers!
Select
Add answer anonymously...

Codalien Technologies Software Engineer interview questions & answers

A Software Engineer was asked Q. Describe how you would build an authentication system for a bank.
A Software Engineer was asked Q. Anagram Substring Search Given two strings 'STR' and 'PTR', identify all startin...read more
A Software Engineer was asked Q. Construct Complete Binary Tree Problem Statement Given an array or list 'ARR' co...read more

Popular interview questions of Software Engineer

A Software Engineer was asked Q1. Describe how you would build an authentication system for a bank.
A Software Engineer was asked Q2. Anagram Substring Search Given two strings 'STR' and 'PTR', identify all startin...read more
A Software Engineer was asked Q3. Construct Complete Binary Tree Problem Statement Given an array or list 'ARR' co...read more
Codalien Technologies Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits