100 Days Coding Blog Challange
Achyuth pv
Posted on October 6, 2024
Hi, today is my first day writing a blog on Medium, and I am thrilled to share my knowledge via blogs, reach people, and help them with real-life and coding challenges. So Let's go coders!!!
Find the Difference — LeetCode Solution in a Nutshell! 🔍
Ever played a game of “spot the difference”? Well, today we’re doing just that, but with strings! Let’s dive into LeetCode’s Find the Difference problem, where you’re given two strings and one of them has an extra character. Your job? Find that extra letter! 🕵️
Problem Breakdown:
Input: Two strings, s and t. String t is created by shuffling s and adding one random extra character.
Example:
s = "abcd"
t = "abcde"
Output:
Find the extra character in t—in this case, it’s e.
The Simple Approach 💡
We can solve this elegantly by making use of ASCII values! Here’s the plan:
Convert characters to ordinals: Use Python’s ord() function to turn characters into numbers (their ASCII values).
Sum the differences: If you sum the ordinals of all characters in both strings, the difference between the two sums will give you the extra character.
Return the character: Use chr() to convert the difference back into a letter.
Python Code:
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
# Sum the ordinals of both strings and find the difference
return chr(sum(ord(c) for c in t) - sum(ord(c) for c in s))
Why It Works:
We’re using simple math to find the difference in the two strings in O(n) time.
The logic is clear: by summing the ordinals of the characters, the difference points directly to the added letter.
💥 Output: e
And just like that, you’ve cracked the problem! 🎉 Simple, efficient, and easy to understand — now you’re ready to tackle it on LeetCode or in an interview!
Posted on October 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.