Find a String Within One Mismatch of All
Updated
Problem statement
Given an array of strings strs where every string has the same length, return a string of that length that differs from each string in strs in at most one position. If no such string exists, return an empty string "".
Two strings differ in a position when their characters at that index are not equal. Characters are compared index by index and are never moved.
When more than one string works, choose this way:
- If
strs[0]works, returnstrs[0]. - Otherwise, every string that works differs from
strs[0]in exactly one position. Return the one whose differing position has the smallest index.
Note: in the second case, no two working strings differ from strs[0] at the same index, so the answer is always unique.
Function
findCloseString(strs: String[]) → StringExamples
Example 1
strs = ["abc","abd","xbc"]return = "abc"strs[0] = "abc" differs from "abd" only at index 2 and from "xbc" only at index 0. So strs[0] itself works, and it is returned.
Example 2
strs = ["abcd","abxy","abcy"]return = "abcy"strs[0] = "abcd" differs from "abxy" at indices 2 and 3, so it does not work. A working string must then copy one of those two letters from "abxy".
- Setting index 2 to
"x"gives"abxd", which differs from"abcy"at indices 2 and 3. It does not work. - Setting index 3 to
"y"gives"abcy". It differs from"abcd"and from"abxy"in one position each, and it equals"abcy". It works.
Example 3
strs = ["cat","cog"]return = "cot""cat" and "cog" differ at indices 1 and 2. Both "cot" and "cag" are one position away from each of them. "cot" differs from strs[0] at index 1, which is smaller than index 2, so the answer is "cot".
Example 4
strs = ["ab","ba","aa","bb"]return = ""To be at most one position away from both "ab" and "ba", a string must be "aa" or "bb". But "aa" differs from "bb" in two positions, and "bb" differs from "aa" in two positions. No string works.
Constraints
1 <= strs.length <= 10001 <= strs[i].length <= 100- All strings in
strshave the same length. strs[i]consists of lowercase English letters.
More Barclays Online Assessment questions
Similar questions at other companies
- Count Subarrays Matching a Comparison PatternTikTok · OA
- Earliest Time to Schedule a MeetingMathWorks · OA
- Earliest Meeting Start on a 24-Hour ClockIMC Trading · OA
- Compress Editor Actions into Operational Transform OperationsReplit · OA · PHONE SCREEN · ONSITE INTERVIEW
- Count One-Swap Number PairsCapital One · OA
- Earliest Time to Schedule a MeetingMicrosoft · OA
- Nested Recipe Blocks (Game Adaptation)Roblox · OA
- Maximize Workday EarningsCitadel · OA · PHONE SCREEN · ONSITE INTERVIEW
- Maximum Equal Parts for PrefixesAmazon · OA
- Best TV Show in a GenreAdyen · OA