Problem · String

Find Last Character

Learn this problem
MediumGoogleOA
See Google hiring insights

Problem statement

You are given an alphanumeric string S and an integer K. Consider a new string in which S is appended K-1 times. Now, in this new string, the following operations are performed:-

  • Every alternate character starting from the first character is removed.
  • Every alternate character starting from the last character is removed.
  • The above two operations are repeated until one character remains. Your task is to find and return a string representing the last remaining character after performing all the operations.

    Note: Here, alphanumeric refers to the string that may contain alphabets (a-z and A-Z), numerals (0-9), and certain special characters such as '$', '#', '&', and '*'

    Input Specification:

    input1: A string S, representing the alphanumeric string.
    input2: An integer value K.

    Output Specification:

    Return a string representing the last remaining character after performing all the operations mentioned.

    Function

    findLastCharacter(S: String, K: int) → String

    Examples

    Example 1

    S = "abcd"K = 3return = "b"
    The following operations can be performed on the string "abcd":
  • S = a b c d a b c d a b c d (The string obtained after appending the given string K-1 times)
  • S = b d b d b d (The string obtained after removing every alternate character from the beginning)
  • S = b b b (The string obtained after removing every alternate character from the end)
  • S = b
  • Since, b is the only character left after performing all the operations. Therefore, b is returned as the output.

    Example 2

    S = "j#k&h"K = 5return = "&"
    The following operations can be performed on the string "j#k&h":
  • S = j # k & h j # k & h j # k & h j # k & h j # k & h (The string obtained after appending the given string K-1 times)
  • S = # & j k h # & j k h # & (The string obtained after removing every alternate character from the beginning)
  • S = # j h & k # (The string obtained after removing every alternate character from the end)
  • S = j & # (The string obtained after removing every alternate character from the beginning)
  • S = &
  • & is the only character left after performing all the operations. Therefore, & is returned as the output.

    Constraints

    • 1 <= S.length <= 10^5
    • 1 <= K <= 10^9
    • S contains letters, digits, or the characters $, #, &, and *.
    • S.length * K fits in a signed 64-bit integer.

    More Google problems

    drafts saved locally
    public String findLastCharacter(String S, int K) {
      // write your code here
    }
    
    S"abcd"
    K3
    expected"b"
    checking account