← Questions

Count letters whose lowercase copies all come before uppercase

0
MicrosoftCoding

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

strings · hashing · counting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding