Replace Characters With the Nearest Prime Code
Updated
Problem statement
Every character has an ASCII code. For example, A is 65, B is 66 and Z is 90. A prime number is a whole number greater than 1 whose only divisors are 1 and itself.
You are given a string s. Build a new string of the same length, one character at a time:
- If the character's code is prime, keep the character.
- Otherwise, replace it with the character whose code is the prime number closest to its code. If a prime below and a prime above are equally close, use the smaller one.
Return the new string.
Function
replaceWithNearestPrime(s: String) → StringExamples
Example 1
s = "HELLO"return = "GCIIO"H is 72. The primes 71 and 73 are both 1 away, so the smaller one wins: 71 is G. E is 69. The primes 67 and 71 are both 2 away, so it becomes 67, which is C. L is 76. The primes 73 and 79 are both 3 away, so each L becomes 73, which is I. O is 79, a prime, so it stays. The answer is "GCIIO".
Example 2
s = "NUTANIX"return = "OSSCOIY"N (78) becomes 79, O. U (85) is 2 away from 83 and 4 away from 89, so it becomes 83, S. T (84) becomes 83, S. A (65) is 2 away from 67 and 4 away from 61, so it becomes 67, C. I (73) is prime and stays. X (88) becomes 89, Y. The answer is "OSSCOIY".
Example 3
s = "CGIOSY"return = "CGIOSY"The codes are 67, 71, 73, 79, 83 and 89. All of them are prime, so nothing changes.
Constraints
1 <= s.length <= 10^4sconsists only of capital English letters (AtoZ).
More Nutanix Online Assessment questions
- Good SubsequencesOA · Seen Jul 2026
- Min Cost to Connect All PointsOA · Seen Jun 2026
- Digit Changes for a Multiple of 9OA · Seen Aug 2025
- Gas Station Loop StartOA · Seen Aug 2025
- Number of Players (for MTS2)OA · Seen Oct 2024
- Work Schedules (for MTS2)OA · Seen Oct 2024
- Minimum Operations to Convert ArrayOA · Seen Apr 2024
- No Adjacent CharactersOA · Seen Apr 2024
- Build a BST From a ListOA · Seen Nov 2022
- Delete Even-Valued Nodes From a Linked ListOA · Seen Nov 2022
Similar questions at other companies
- Identification Number Check DigitAbridge · OAAbridge interview questions
- Count Substrings With Identical CharactersVirtu Financial · OAVirtu Financial interview questions
- Count Multiples of Three with Two SevensHudson River Trading · OAHudson River Trading interview questions
- Is This Date a Weekend?Salesforce · OASalesforce interview questions
- Triple-Position Alphabet EncodingArm · OA
- Closest ColorTwo Sigma · OATwo Sigma interview questions
- Prime Number From a StringAdobe · OAAdobe interview questions
- Sum Integer StringsIntuit · OAIntuit interview questions
- Count Times Using at Most Two DigitsLSEG · OALSEG interview questions
- Valid String CheckUber · OAUber interview questions