↓Skip to main content
  1. LeetCode/

LeetCode 942: DI String Match

·1 min· ·
LeetCode Easy Array Two-Pointers String Greedy
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-26

  • Submissions: Accepted ×3

Approach
#

lo = 0 and hi = n are the smallest and largest unused values. On I place lo, since everything placed later is larger; on D place hi, since everything later is smaller. At the end lo == hi; append it.

My Solution
#

class Solution:
    def diStringMatch(self, s: str) -> List[int]:
        lo, hi = 0, len(s)
        res = []
        for ch in s:
            if ch == "I":
                res.append(lo)
                lo += 1
            else:
                res.append(hi)
                hi -= 1
        res.append(lo)
        return res

Complexity
#

Time O(n), space O(n) (output).

Mistakes to Avoid
#

  • The answer has n + 1 numbers; append the last one after the loop.

Interview Explanation
#

Two pointers track the smallest and largest unused values; I takes the smallest and D the largest, so the next number always fits, and the one left over goes at the end. Time O(n).

Related

LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum
LeetCode 680: Valid Palindrome II
·2 mins
LeetCode Easy Two-Pointers String Greedy
LeetCode 680 note: at the first mismatch the only options are deleting the left or the right character; check whether either remainder is a palindrome
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 804: Unique Morse Code Words
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 804 note: translate each word into a Morse string and count the distinct results with a set
LeetCode 557: Reverse Words in a String III
·1 min
LeetCode Easy Two-Pointers String
LeetCode 557 note: split on spaces, reverse each word, and join with spaces
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row