↓Skip to main content
  1. LeetCode/

LeetCode 1078: Occurrences After Bigram

·1 min· ·
LeetCode Easy String
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-10-04

  • Submissions: Runtime Error → Accepted ×3

Approach
#

Split into words and check each i (String Template 6): if words[i] == first and words[i + 1] == second, collect words[i + 2]. Looping only to len(words) - 2 guarantees the third word exists.

My Attempts
#

Attempt 1 checked only i + 1 < len(text) but read text[i + 2]: "b b" with first = second = "b" raised IndexError. Checking i + 2 passed.

Solution
#

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        w = text.split()
        return [w[i + 2] for i in range(len(w) - 2)
                if w[i] == first and w[i + 1] == second]

Complexity
#

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

Mistakes to Avoid
#

  • Since i + 2 is accessed, bound-check i + 2.

Interview Explanation
#

I split into words and check every window of three, collecting the third when the first two equal first and second, looping only up to the third-to-last word. Time O(n).

Related

LeetCode 1047: Remove All Adjacent Duplicates In String
·1 min
LeetCode Easy String Stack
LeetCode 1047 note: if the stack top equals the current character both vanish, otherwise push it; after a removal the new top may cancel with the next character
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand
LeetCode 1021: Remove Outermost Parentheses
·1 min
LeetCode Easy String Stack Bracket-Sequences
LeetCode 1021 note: track depth instead of a stack; the ‘(’ raising depth from 0 to 1 and the ‘)’ lowering it from 1 to 0 are outermost, everything else stays
LeetCode 929: Unique Email Addresses
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 929 note: split at @, normalize only the local part (drop everything after +, remove dots), rejoin with the domain and collect in a set
LeetCode 944: Delete Columns to Make Sorted
·1 min
LeetCode Easy Array String Longest-Increasing-Subsequence
LeetCode 944 note: take each column with zip(*strs) and count the columns that are not non-decreasing
LeetCode 953: Verifying an Alien Dictionary
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 953 note: map letters to their alien index and compare each adjacent pair at the first differing character; with no difference, the shorter must come first