SkillByAIइंटरैक्टिव संस्करण खोलें →

पाठ 6 / 42

Stack

push, pop और peek वाला last-in-first-out stack उपयोग करें और balanced brackets, undo और DFS में लागू करें।

LIFO

आप हमेशा केवल शीर्ष तत्व को छूते हैं। push, pop, और peek सभी O(1)। Array (append/pop) या linked list (head पर insert/remove) से समर्थित।

प्लेटों का ढेर

आप शीर्ष से प्लेट जोड़ते और लेते हैं। पहली रखी प्लेट आख़िर में उठती है।

संतुलित कोष्ठक

खुलने पर push, बंद होने पर pop और मिलान। अंत में खाली stack का अर्थ संतुलित।

def is_balanced(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    st = []
    for c in s:
        if c in '([{':
            st.append(c)
        elif not st or st.pop() != pairs[c]:
            return False
    return not st

Output:

is_balanced("({[]})") -> True
is_balanced("(]")     -> False

यह कहाँ छिपा है

फ़ंक्शन call stack, undo/redo, ब्राउज़र इतिहास, अभिव्यक्ति मूल्यांकन, DFS, और "next greater element" (monotonic stack)।