-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path389_Find_the_Difference.js
More file actions
59 lines (52 loc) · 1.76 KB
/
389_Find_the_Difference.js
File metadata and controls
59 lines (52 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
*/
const expect = require('expect');
describe('389 Find the Difference', () => {
it('returns the difference between two strings', () => {
//arragne
const input1 = 'abcdeghijk';
const input2 = 'kabcjihgedf';
const expected = 'f';
//act
const actual = findTheDifference(input1, input2);
//assert
expect(actual).toBe(expected);
});
});
const findTheDifference_1 = (input1, input2) => {
return [...input2].filter(input2Val => {
if (input1.includes(input2Val)) {
const input1Array = [...input1];
input1Array.splice(input1Array.indexOf(input2Val), 1);
input1 = input1Array.join('');
return false;
}
return true;
})[0];
};
const findTheDifference_2 = (input1, input2) => {
if (input1.length === 0) return input2;
const input1Sum = input1
.split('')
.map(e => e.charCodeAt(0)).reduce((a, b) => a + b);
const input2Sum = input2
.split('')
.map(e => e.charCodeAt(0)).reduce((a, b) => a + b);
return String.fromCharCode(input2Sum - input1Sum);
};
// Use the commutative property of xor and the fact that A^A === 0
const findTheDifference_3 = (input1, input2) => {
let charCode = input2.charCodeAt(input2.length - 1);
[...input1].forEach((value, index) => {
charCode = charCode ^ input1.charCodeAt(index) ^ input2.charCodeAt(index);
});
return String.fromCharCode(charCode);
};
const findTheDifference = (input1, input2) => {
const charCode = [...input1, ...input2].reduce((acc, cur) => acc ^ cur.charCodeAt(0), 0);
return String.fromCharCode(charCode);
};