FastPrepSwap Adjacent Character Pairs

Swap Adjacent Character Pairs

Hartford Financial Services logoHartford Financial Services● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a string text, swap the two characters in every consecutive, nonoverlapping pair, starting from the beginning, and return the resulting string.

The pairs use zero-based positions (0, 1), (2, 3), and so on. If the length is odd, leave the final unpaired character unchanged. Preserve the order of the pairs.

For example, abcd becomes badc.

Function

swapAdjacentPairs(text: String) → String

Examples

Example 1

text = "abcd"return = "badc"

Swap a with b, then c with d. This input/output pair appears in the report.

Example 2

text = "abcde"return = "badce"

The pairs are swapped, while the final e has no partner and stays unchanged.

Example 3

text = "a"return = "a"

There is no complete pair, so the string stays unchanged.

Constraints

  • 1 <= text.length <= 10^5.
  • text contains only lowercase English letters a through z.

More Hartford Financial Services problems

See Hartford Financial Services hiring insights
public String swapAdjacentPairs(String text) {
    // write your code here
}
text"abcd"
expected"badc"
Checking account…