Taro Logo

Find Valid Pair of Adjacent Digits in String

#28 Most AskedEasy
40 views
Topics:
Strings

You are given a string s consisting only of digits. A valid pair is defined as two adjacent digits in s such that:

  • The first digit is not equal to the second.
  • Each digit in the pair appears in s exactly as many times as its numeric value.

Return the first valid pair found in the string s when traversing from left to right. If no valid pair exists, return an empty string.

Example 1:

Input: s = "2523533"

Output: "23"

Explanation:

Digit '2' appears 2 times and digit '3' appears 3 times. Each digit in the pair "23" appears in s exactly as many times as its numeric value. Hence, the output is "23".

Example 2:

Input: s = "221"

Output: "21"

Explanation:

Digit '2' appears 2 times and digit '1' appears 1 time. Hence, the output is "21".

Example 3:

Input: s = "22"

Output: ""

Explanation:

There are no valid adjacent pairs.

Constraints:

  • 2 <= s.length <= 100
  • s only consists of digits from '1' to '9'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible length of the input string `num`?
  2. Can the input string `num` be empty or null?
  3. Is the input string `num` guaranteed to contain only digit characters (0-9)?
  4. If multiple pairs of adjacent digits sum to 10, should I return true after finding the first such pair, or do I need to check the entire string?
  5. Besides returning `true` or `false`, are there any specific output requirements or formatting expectations?

Brute Force Solution

Approach

The brute force approach to finding a valid pair of adjacent digits involves checking every possible pair in the string. We examine each consecutive set of two digits and determine if it meets our criteria. This method guarantees finding a solution if one exists because it explores all possibilities.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the string.
  2. Look at the first two digits next to each other.
  3. Check if these two digits satisfy the condition we are looking for (e.g., their sum is even, one is larger than the other, etc.).
  4. If they do, we have found a valid pair, and we are done.
  5. If not, move to the next pair of digits by shifting one position to the right.
  6. Repeat the process of checking if the new pair satisfies the condition.
  7. Keep doing this until you either find a valid pair or you reach the end of the string.
  8. If you reach the end of the string without finding a valid pair, then there is no such pair in the string.

Code Implementation

def find_valid_pair_of_adjacent_digits(input_string):
    string_length = len(input_string)

    # Iterate up to the second-to-last digit
    for index in range(string_length - 1):
        first_digit = input_string[index]
        second_digit = input_string[index + 1]

        # Check if the pair is valid.
        if is_valid_pair(first_digit, second_digit):
            return True

    return False

def is_valid_pair(first_digit, second_digit):
    # Define the rule for a valid pair: sum of the digits must be odd
    if (int(first_digit) + int(second_digit)) % 2 != 0:
        return True
    else:
        return False

Big(O) Analysis

Time Complexity
O(n) – The algorithm iterates through the string of length n, examining each adjacent pair of digits exactly once. For each pair, it performs a constant-time check to determine if the pair is valid. Since the number of pairs is directly proportional to the length of the string, the total number of operations scales linearly with n. Therefore, the time complexity is O(n).
Space Complexity
O(1) – The algorithm iterates through the string, examining pairs of adjacent digits. It does not create any auxiliary data structures like lists, maps, or sets to store intermediate results or keep track of visited positions. The space used is limited to storing a fixed number of variables, such as indices or temporary variables for comparison, and does not depend on the length of the input string, N. Therefore, the space complexity is constant.

Optimal Solution

Approach

The goal is to efficiently find if a string contains two adjacent digits that satisfy a given condition. The optimal approach involves examining each pair of consecutive characters in the string one by one, stopping as soon as a valid pair is identified.

Here's how the algorithm would work step-by-step:

  1. Start at the beginning of the string.
  2. Look at the first two characters.
  3. Check if both are digits (0 through 9).
  4. If both are digits, apply the condition (e.g., sum of digits is less than a threshold).
  5. If the condition is met, report that a valid pair has been found and stop.
  6. If the condition is not met or if the first two characters are not both digits, move to the next pair of characters (the second and third characters).
  7. Repeat the process of checking if both are digits and applying the condition.
  8. Continue until you find a valid pair or reach the end of the string.
  9. If you reach the end of the string without finding a valid pair, report that no such pair exists.

Code Implementation

def find_valid_pair(number_string):
    string_length = len(number_string)

    for index in range(string_length - 1):
        first_digit = int(number_string[index])
        second_digit = int(number_string[index + 1])

        # Check if the current pair of digits meets the condition.
        if first_digit + second_digit < 10:

            # If the condition is met, return True immediately.
            return True

    # If no valid pair is found after checking all pairs, return False.
    return False

Big(O) Analysis

Time Complexity
O(n) – The algorithm iterates through the input string of size n, examining pairs of adjacent characters. For each pair, it performs a constant amount of work: checking if both are digits and applying the condition. The algorithm stops immediately once a valid pair is found, or it iterates through all n-1 pairs in the worst case. Therefore, the time complexity is directly proportional to the length of the string, resulting in O(n).
Space Complexity
O(1) – The algorithm iterates through the input string, examining pairs of adjacent characters. It does not create any auxiliary data structures like arrays, hash maps, or lists to store intermediate results or visited locations. The only space used is for a few constant-size variables, such as loop counters or temporary storage for character values during the comparison. Therefore, the space complexity remains constant regardless of the input string size N.

Edge Cases

Null or empty string input
How to Handle:
Return false immediately as there are no digits to form a pair.
String with a single digit
How to Handle:
Return false since a pair of adjacent digits is impossible to form.
String with only two digits that sum to 10
How to Handle:
The algorithm should correctly identify this as a valid pair and return true.
String with no adjacent digits that sum to 10
How to Handle:
The algorithm should iterate through the string without finding a matching pair and return false.
String with leading zeros
How to Handle:
The algorithm should treat leading zeros as valid digits and process them accordingly, considering adjacent digits for the sum of 10.
String with very long length
How to Handle:
The algorithm should iterate through the string linearly, so the time complexity will be O(n), where n is the length of the string, and should remain efficient.
String with non-digit characters
How to Handle:
The prompt specifies the string consists of digits so we will assume that non-digit characters will not be present.
String where multiple pairs sum to 10
How to Handle:
The algorithm should return true as soon as it finds the first valid pair.
0/256 completed