FastPrepReverse a String Keeping Dashes in Place

Reverse a String Keeping Dashes in Place

Nykaa logoNykaa● EasyFULLTIMEONSITE INTERVIEW

Problem statement

You are given a string s made of English letters, digits, and dashes (-).

Reverse the order of all the characters that are not dashes, but keep every dash at the same index it has in s. Return the new string.

Function

reverseKeepingDashes(s: String) → String

Examples

Example 1

s = "ab-cde"return = "ed-cba"

The characters that are not dashes are a, b, c, d, e. In reverse order they are e, d, c, b, a. They fill the non-dash positions from left to right, and the dash stays at index 2, giving "ed-cba".

Example 2

s = "2026-11-07"return = "7011-62-02"

The digits 2026, 11, 07 read 20261107 without the dashes. Reversed, that is 70116202. Putting the dashes back at indexes 4 and 7 gives "7011-62-02".

Example 3

s = "-a--Bc"return = "-c--Ba"

The dashes at indexes 0, 2, and 3 stay where they are. The other characters a, B, c are reversed to c, B, a, giving "-c--Ba".

Constraints

  • 1 <= s.length <= 10^4
  • Every character of s is an English letter (a to z or A to Z), a digit (0 to 9), or a dash (-).

More Nykaa problems

See Nykaa hiring insights
Saved
public String reverseKeepingDashes(String s) {
    // Write your code here.
}
Checking account…