Find the Difference LeetCode Solution - The Coding Shala
Home >> LeetCode >> Find the Difference
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Find the Difference Problem and will implement its solution in Java.
Find the Difference Problem
You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Practice this problem on LeetCode.
LeetCode - Find the Difference Java Solution
Approach 1
Using HashMap.
Java Program:
class Solution { public char findTheDifference(String s, String t) { Map<Character, Integer> map = new HashMap<>(); for(int i=0; i<s.length(); i++) { if(map.containsKey(s.charAt(i))) { map.put(s.charAt(i), map.get(s.charAt(i))+1); } else { map.put(s.charAt(i), 1); } } for(int i=0; i<t.length(); i++) { if(!map.containsKey(t.charAt(i)) || map.get(t.charAt(i)) == 0) { return t.charAt(i); } else { map.put(t.charAt(i), map.get(t.charAt(i))-1); } } //ignore this return; return ' '; } }
Approach 2
Using Bit Manipulation.
If we do xor in both the string only additional char will remain.
Java Program:
class Solution { public char findTheDifference(String s, String t) { char ch = t.charAt(t.length()-1); for(int i=0; i<s.length(); i++) { ch ^= s.charAt(i); ch ^= t.charAt(i); } return ch; } }
- Binary Number with Alternating Bits
- LeetCode - Letter Case Permutation
- LeetCode - Valid Boomerang
- LeetCode - Split a String in Balanced Strings
- LeetCode - Crawler Log Folder
Comments
Post a Comment