Count letters whose lowercase copies all come before uppercase
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests strings, hashing and counting.
Given a string s of English letters (it may also contain other characters, which you ignore), count the distinct letters, compared case-insensitively, that satisfy this rule:
Every lowercase occurrence of the letter appears before every uppercase occurrence of the same letter.
A letter that appears only in lowercase, or only in uppercase, satisfies the rule.
Implement:
def count_ordered_letters(s: str) -> int: ...
Constraints
0 <= len(s) <= 10^5- Aim for O(n) time.
Example 1
Input: s = "xxXyYyz"
Output: 2
x: both lowercase copies come before X, so it counts. y: a lowercase y follows Y, so it does not. z: lowercase only, so it counts.
Example 2
Input: s = "Hello hELLO"
Output: 3
e, l and o count. h does not, because a lowercase h follows H.
Clarifying questions
- Are only ASCII letters counted, or also letters like
éandÉ? - Does a letter that never appears count? (No: only letters that appear in
s.) - Does the empty string return
0? - Should we return the letters too, or only the count?
What a strong answer covers
- Keeps two arrays of 26 entries: the last index of each lowercase letter and the first index of each uppercase letter.
- Counts a letter when it appears in only one case, or when its last lowercase index is below its first uppercase index.
- Skips non-letters. That is O(n) time and O(1) memory.
- Tests
"xxXyYyz","Hello hELLO", a string of only digits, a letter in only one case, and a lowercase copy right after the uppercase one.
Follow-ups
- Return the letters in alphabetical order.
- The opposite rule: every uppercase copy comes first.
- A stream of characters with the count asked at any time.
- The fewest characters to delete so that every letter follows the rule.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
