713971. Valid Compressed String

Medium

Valid Compressed String

Slug: valid-compressed-string--170647

Difficulty: Medium

Id: 713971

Topic Tags: Strings, Greedy, Data Structures, Algorithms

Company Tags: Facebook

Summary

Given a compressed string, determine whether it is valid or not. A compressed string is considered valid if it can be decompressed into an original string without any characters being overwritten. For example, the compressed string "a3[bc]" is valid because it can be decompressed into the original string "aabcbc". On the other hand, the compressed string "a2[abc]" is not valid because the character 'c' would overwrite the existing 'b'. The input string only contains lowercase English letters and digits.

Detailed Explanation

The approach to solve this problem involves using a greedy algorithm. Iterate through the compressed string and check if each digit is followed by an opening bracket '[' or not. If it's not, then the compressed string is invalid. However, if it is, then check if there are enough characters in the original string to accommodate the decompressed string of the given length. If there are not, then the compressed string is also invalid.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty stack.
  2. Iterate through the compressed string.
  3. For each character:
    • If it's a digit, push it onto the stack.
    • If it's an opening bracket '[' and there are characters in the stack, pop all the characters from the stack until you find the corresponding closing bracket ']' or the stack becomes empty.
  4. After iterating through the entire string, check if the stack is empty. If it is, then the compressed string is valid. Otherwise, it's invalid.

Time complexity: O(n), where n is the length of the compressed string. Space complexity: O(m), where m is the maximum number of characters that can be pushed onto the stack at any given time (which is equal to the maximum value of a digit in the compressed string).

Optimized Solutions

Java

View on GeeksforGeeks
public boolean isValidCompressedString(String s) {
    int i = 0, n = s.length();
    while (i < n) {
        if (!Character.isDigit(s.charAt(i))) {
            i++;
            continue;
        }
        int j = i + 1;
        while (j < n && Character.isDigit(s.charAt(j))) {
            j++;
        }
        if (s.charAt(j) != '[') {
            return false;
        }
        i = j + 1;
    }
    return true;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.