Shortest Window Substring in Order πŸ‚ - Google Top Interview Questions

Problem Statement :

Given a lowercase alphabet string s, return the length of the shortest substring containing all alphabet characters in order from "a" to "z". If there's no solution, return -1.


0 ≀ n ≀ 100,000 where n is the length of s

Example 1


s = "aaaaabcbbdefghijklmnopqrstuvwxyzzz"




The shortest such substring is "abcbbdefghijklmnopqrstuvwxyz". The two additional "b"s contribute to 
the 2 extra characters.

Example 2


s = "zyxwvutsrqponmlkjihgfedcba"




Even though this string has all the characters in the alphabet, it's not in order from "a" to "z".

Solution :


                        Solution in C++ :

int solve(string s) {
    vector<vector<int>> adj(26);
    for (int i = 0; i < s.length(); i++) {
        adj[s[i] - 'a'].push_back(i);
    int ans = 1e7;
    for (auto& r : adj) sort(r.begin(), r.end());
    for (int i = 0; i < adj[0].size(); i++) {
        int s = adj[0][i], curr = 1, next = adj[0][i];
        while (curr != 26) {
            int temp_next =
                upper_bound(adj[curr].begin(), adj[curr].end(), next) - adj[curr].begin();
            if (temp_next == adj[curr].size()) break;
            next = adj[curr][temp_next];
            curr += 1;
        if (curr == 26) ans = min(ans, next - s + 1);
    return ans == 1e7 ? -1 : ans;

                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(String s) {
        int[] dp0 = new int[26], dp1 = new int[26]; // position, length
        Arrays.fill(dp0, -1);
        int res = Integer.MAX_VALUE;
        for (int j = 0; j != s.length(); j++) {
            final int ch = s.charAt(j) - 'a';
            if (ch == 0) {
                dp0[ch] = j;
                dp1[ch] = 1;
            } else {
                if (dp0[ch - 1] != -1) {
                    dp0[ch] = j;
                    dp1[ch] = j - dp0[ch - 1] + dp1[ch - 1];
                if (dp0[25] != -1) {
                    res = Math.min(res, dp1[25]);
        return res == Integer.MAX_VALUE ? -1 : res;

                        Solution in Python : 
class Solution:
    def solve(self, S):
        inds = [[] for _ in range(26)]
        for i, c in enumerate(S):
            inds[ord(c) - ord("a")].append(i)

        roots = {i: i for i in inds[0]}
        for row1, row2 in zip(inds, inds[1:]):
            roots2 = {}
            i = 0
            for jx in row2:
                while i < len(row1) and jx > row1[i]:
                    if row1[i] in roots:
                        roots2[jx] = roots[row1[i]]
                    i += 1

            roots = roots2

        return min(k - v + 1 for k, v in roots.items()) if roots else -1

View More Similar Problems


We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution β†’

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution β†’

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution β†’

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution β†’

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution β†’

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution β†’