Verify Nickname Subsequence — Problem Statement & Solution Guide

StringsEasyTwo Pointers
TimeO(N)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Strings and solve the Verify Nickname Subsequence problem optimally.

TopicStrings
PatternTwo Pointers
TimeO(N)
SpaceO(1)

Problem Description

You are tasked with validating whether a specific string, referred to as the nickname, is a subsequence of a longer string, the full name. A string A is considered a subsequence of string B if A can be formed by deleting zero or more characters from B without altering the relative order of the remaining characters. The validation process must be case-insensitive, meaning that 'A' and 'a' are treated as identical characters during comparison.

Given two strings, fullName and nickname, return true if nickname is a valid subsequence of fullName; otherwise, return false. The solution should efficiently determine this relationship by traversing both strings, ensuring that each character in nickname is found in fullName in the correct sequential order.

The input consists of two strings: fullName, which represents the complete name, and nickname, which is the candidate subsequence. The output is a boolean value indicating the validity of the nickname as a subsequence of the fullName.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Verify Nickname Subsequence"

easy

WHY DOES IT MATTER?

The subsequence pattern is fundamental because it models real-world scenarios where order matters but contiguity does not, such as pattern matching in logs, DNA sequence alignment, or user input validation. Mastering this pattern demonstrates an understanding of greedy algorithms and efficient string processing, which are core competencies for backend and systems engineering roles.

OPTIMIZATION CHALLENGE

The key insight is that you do not need to backtrack. Once a character in the target string is matched, you never need to look at previous characters in the source string again. This allows a single forward pass, reducing time complexity from quadratic to linear.

REAL-WORLD CONNECTION

This is analogous to verifying if a specific sequence of events occurred in a distributed system's event log. For example, checking if 'User Login' -> 'Payment Initiated' -> 'Payment Success' occurred in order, even if other events (like 'User Clicked Ad') happened in between. The two-pointer approach efficiently scans the log once to verify the critical path.

In interviews, explicitly state the time complexity as O(N) where N is the length of the longer string, and emphasize that you are not using recursion or dynamic programming, which would be overkill. Mentioning the early termination condition (if target length > source length) shows attention to detail and performance optimization.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The subsequence problem is a classic application of the Two Pointers technique, specifically the 'Greedy Matching' strategy. The core theoretical insight is that if a character in the target string (nickname) matches the current character in the source string (full name), we must advance the pointer for the target string. This greedy choice is optimal because delaying the match would only restrict future possibilities; if a character can be matched now, matching it immediately leaves the maximum number of remaining characters in the source string to satisfy the rest of the target. This relies on the property that relative order is preserved, but contiguity is not required.

Naive approaches, such as generating all possible subsequences of the full name to check if the nickname exists among them, are computationally infeasible for large inputs. The number of subsequences of a string of length N is 2^N, leading to exponential time complexity O(2^N * M), which fails for any realistic input size (e.g., N > 30). Even a simple nested loop approach that restarts the search for the next nickname character from the beginning of the full name for every step results in O(N*M) time complexity, which is suboptimal compared to the linear solution.

The optimal paradigm is a single-pass linear scan using two pointers. One pointer iterates through the full name, and the other tracks the current position in the nickname. By processing the full name exactly once, we achieve O(N) time complexity (where N is the length of the full name), which is the theoretical lower bound since we must inspect every character in the source string at least once to ensure no valid subsequence is missed. This approach is space-efficient, requiring only O(1) auxiliary space, making it ideal for memory-constrained environments and high-throughput systems.

Interview Questions on This Problem

Q1At a fintech platform like Stripe, we need to validate if a user's preferred short ID is a subsequence of their full transaction ID for logging purposes. How would you handle case-insensitivity and Unicode characters efficiently?

I would use the two-pointer approach. First, I would normalize both strings to lowercase using a locale-aware method to handle Unicode correctly. Then, I would iterate through the transaction ID with one pointer and the short ID with another. If characters match, I advance the short ID pointer. If the short ID pointer reaches the end, it is a valid subsequence. This runs in O(N) time where N is the length of the transaction ID, ensuring low latency for high-volume transaction logging.

Q2In a high-growth startup building a real-time chat system, we want to detect if a user's 'handle' is a subsequence of their 'display name' to suggest profile consistency. What are the edge cases you would consider?

Key edge cases include: 1) Empty handle (always true, as an empty string is a subsequence of any string). 2) Handle longer than display name (always false). 3) Case sensitivity (must be handled per product requirements, usually case-insensitive). 4) Special characters and whitespace (decide if they are ignored or treated as characters). 5) Unicode normalization (e.g., 'é' vs 'e' + combining accent). I would implement the two-pointer solution with early termination if the handle length exceeds the display name length.

Q3At a global product company like Amazon, we process millions of product names daily. If we need to check if a 'brand keyword' is a subsequence of a 'product title', how would you optimize this for a batch of 1 million queries against the same product title?

For a single query, two pointers is optimal. However, for 1 million queries against the same title, I would preprocess the title to build a next-occurrence table or a list of indices for each character. This allows each query to be answered in O(K) time, where K is the length of the brand keyword, by jumping directly to the next occurrence of the required character. This reduces the total time from O(M * N) to O(N + M * K), which is significantly faster for large M.

Examples

Example 1

Input

fullName = "Alexander Hamilton", nickname = "Alex H"

Output

true

Explanation: Convert both strings to lowercase: "alexander hamilton" and "alex h". 1. Find 'a' in fullName at index 0. 2. Find 'l' in fullName at index 1. 3. Find 'e' in fullName at index 2. 4. Find 'x' in fullName at index 3. 5. Find 'h' in fullName at index 9 (after 'x'). All characters of nickname are found in order. Return true.

Example 2

Input

fullName = "John Smith", nickname = "Jhon S"

Output

false

Explanation: Convert to lowercase: "john smith" and "jhon s". 1. Find 'j' at index 0. 2. Find 'h' at index 1. 3. Look for 'o' after index 1. The next character is 'n' at index 2, then ' ' at 3, 's' at 4. 'o' is not found after 'h'. Since 'o' cannot be found in the correct order, return false.

Example 3

Input

fullName = "Grace Hopper", nickname = "G H"

Output

true

Explanation: Convert to lowercase: "grace hopper" and "g h". 1. Find 'g' at index 0. 2. Find 'h' at index 6 (after 'g'). Both characters are found in order. Return true.

Example 4

Input

fullName = "Ada Lovelace", nickname = "A L"

Output

true

Explanation: Convert to lowercase: "ada lovelace" and "a l". 1. Find 'a' at index 0. 2. Find 'l' at index 4 (after 'a'). Both characters are found in order. Return true.

Constraints

  • 1 <= fullName.length <= 10^5
  • 1 <= nickname.length <= 10^5
  • fullName and nickname consist of uppercase and lowercase English letters and spaces.
  • The comparison is case-insensitive.

Optimal Approach & Strategy

Use two pointers to scan the full name once, advancing the nickname pointer only when a match is found. This achieves linear time complexity O(N) and constant space complexity O(1).

Brute Force Approach

Generate all possible subsequences of the full name and check if the nickname is among them. This approach has exponential time complexity O(2^N) and is infeasible for large inputs.

Code Solutions

JavaScript Solution
Time: O(N)
function isSubsequence(fullName, nickname) {
    let i = 0, j = 0;
    while (i < fullName.length && j < nickname.length) {
        if (fullName[i] === nickname[j]) {
            j++;
        }
        i++;
    }
    return j === nickname.length;
}

Asked in Top Tech Interviews

Infosys

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.