EasyNo. 2451

Odd String Difference — LeetCode 2451 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, String
Reading time
2 min

The problem

You are given an array of equal-length strings words. Assume that the length of each string is n.

Example

Input
words = ["adc","wzy","abc"]
Output
"abc"
Explanation
- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1].

Python solution

PythonSolution
class Solution:
    def oddString(self, words: List[str]) -> str:
        d = defaultdict(list)
        for s in words:
            t = tuple(ord(b) - ord(a) for a, b in pairwise(s))
            d[t].append(s)
        return next(ss[0] for ss in d.values() if len(ss) == 1)

Complexity

Time
O(m × n)
Space · auxiliary
O(m + n)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2451. Odd String Difference is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2456Most Popular Video CreatorMedium
0049Group AnagramsMedium
0139Word BreakMedium
0140Word Break IIHard
0336Palindrome PairsHard
0500Keyboard RowEasy

Frequently asked questions

How hard is LeetCode 2451. Odd String Difference?

LeetCode 2451. Odd String Difference is rated Easy on LeetCode.

What is the time complexity of LeetCode 2451. Odd String Difference?

The Python solution on this page runs in O(m × n).

What is the space complexity of LeetCode 2451. Odd String Difference?

The Python solution on this page uses O(m + n) auxiliary space.

What topics does LeetCode 2451. Odd String Difference cover?

LeetCode 2451. Odd String Difference is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.