713193. Geeks And The String

Medium

Geeks And The String

Summary

Given a string str and an integer n, find all substrings of length n in str that contain at least one "geek" and exactly one "and". Return these substrings as a list.

This problem involves using a stack data structure to efficiently find the desired substrings.

Detailed Explanation

To solve this problem, we can use a stack-based approach. We iterate through the string str, keeping track of the last n characters in a stack. When we encounter an "and", we pop elements from the stack until we either run out of elements or find a substring that contains at least one "geek". If we find such a substring, we add it to our result list.

Here's a step-by-step breakdown:

  1. Initialize an empty stack s and an empty list result.
  2. Iterate through str, character by character.
  3. For each character:
    • If the character is "and", pop elements from s until we either run out of elements or find a substring that contains at least one "geek".
    • If the popped elements form a valid substring (i.e., it contains at least one "geek" and exactly one "and"), add it to result.
  4. Return result.

Time complexity: O(N), where N is the length of the input string. Space complexity: O(1), since we only use a constant amount of space to store the stack and result list.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class GeeksAndTheString {
    public static List<String> geeksAndTheString(String str, int n) {
        List<String> result = new ArrayList<>();
        Stack<Character> s = new Stack<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == 'a' && s.size() >= n - 1) {
                // Found a valid substring, add it to result
                String temp = "";
                while (!s.isEmpty()) {
                    temp = (char)s.pop() + temp;
                }
                result.add(temp);
            } else if (c != 'a' && c != 'n' && c != 'd') {
                s.push(c);
            } else if (c == 'n') {
                // Found an "and", pop elements until we find a "geek"
                while (!s.isEmpty() && (char)s.peek() != 'g') {
                    s.pop();
                }
                if (!s.isEmpty()) {
                    s.pop(); // Remove the "g" from the stack
                }
            }
        }

        return result;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.