Magicsheet logo

Second Largest Digit in a String

Easy
100%
Updated 6/1/2025

Second Largest Digit in a String

What is this problem about?

The Second Largest Digit in a String interview question gives you a string containing both letters and digits. Your task is to find the second largest numerical digit in the string — considering only the digit characters — and return it. If fewer than two distinct digits exist in the string, return -1. This is a beginner-level string filtering and ranking problem.

Why is this asked in interviews?

Microsoft and Bloomberg ask this problem as a warm-up exercise testing basic string traversal, character classification, digit extraction, and set-based deduplication. It validates that candidates can cleanly separate concerns: filter characters, collect unique values, and apply a ranking operation. Despite its simplicity, it distinguishes candidates who write clean, readable code from those who mix parsing with ranking logic.

Algorithmic pattern used

The pattern is hash table (set) with linear scan. Iterate through the string and collect all unique digit characters into a set. Convert each digit character to its integer value. After processing the full string, sort the unique digits in descending order. If the sorted list has at least 2 elements, return the second element (index 1). Otherwise, return -1. This is O(n) time for the scan and O(1) space (at most 10 distinct digits).

Example explanation

String: "abc3d15f2"

Digit characters: '3', '1', '5', '2'. Unique digits as integers: {1, 2, 3, 5}. Sorted descending: [5, 3, 2, 1]. Second largest: 3.

String: "z9y8" Digits: {8, 9}. Sorted: [9, 8]. Second largest: 8.

String: "hello7world" Digits: {7}. Only one distinct digit → return -1.

Common mistakes candidates make

  • Not deduplicating digits — using a list instead of a set means the same digit counted multiple times could incorrectly influence position.
  • Forgetting to convert character digits to integers before comparison — '9' > '2' works lexicographically but int('9') is cleaner and avoids confusion.
  • Returning the second occurrence rather than the second distinct value — the problem asks for second largest DISTINCT digit.
  • Not handling the case where all digits are the same (e.g., "111") — should return -1.

Interview preparation tip

For the Second Largest Digit in a String coding problem, the hash table string interview pattern is the straightforward approach. In Python, {int(c) for c in s if c.isdigit()} computes the set of unique digit integers in one expression. Bloomberg and Microsoft interviewers use this as a 3-minute problem — solve it cleanly, then offer to discuss the follow-up: "What if you needed the kth largest digit?" Use a sorted set or heapq.nlargest(k, digits). Keeping solutions concise and extensible impresses interviewers.

Similar Questions