-
Notifications
You must be signed in to change notification settings - Fork 2
/
1.2 Check Permutation.js
64 lines (53 loc) · 2.08 KB
/
1.2 Check Permutation.js
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
60
61
62
63
64
/*
Check Permutation: Given two strings, write a method to decide if one is a permutation of the
other.
*/
/*
Assumptions:
1. Characters are in ASCII, not Unicode.
2. Characters are all lower case.
3. Characters are all in the English Alphabet.
4. No spaces are included.
*/
const checkPermutation = (string1, string2) => {
// base case if string lengths do not equal each other
if (string1.length !== string2.length) return false;
// create counter array starting with all 0's with length of 26 for each character of the alphabet for string1
const counterArray1 = new Array(26).fill(0);
// create counter array starting with all 0's with length of 26 for each character of the alphabet for string2
const counterArray2 = new Array(26).fill(0);
// for loop with string1,
for (let i = 0; i < string1.length; i++) {
// count characters by incrementing with counter array for string1
counterArray1[string1[i].charCodeAt(0) - 97] += 1; // 97 is a in ASCII which will be indicate first index
}
// for loop with string2,
for (let i = 0; i < string2.length; i++) {
// count characters by incrementing with counter array for string2
counterArray2[string2[i].charCodeAt(0) - 97] += 1; // 97 is a in ASCII which will be indicate first index
}
// return boolean comparison of the two joined counter arrays
return counterArray1.join('') === counterArray2.join('');
};
// string1 = 'abc', string2 = 'cba' => true
// string1 = 'abc', string2 = 'cbd' => false
// test cases
const argument1a = 'abc';
const argument2a = 'cbd';
const actual = checkPermutation(argument1a, argument2a);
const expected = false;
const testCase = 'Checks if one string is permutation of the other';
const assertEquals = (actual, expected, testCase) => {
if (actual !== expected) {
return `ERROR ${testCase}: Expected ${expected} but got ${actual}`;
}
return 'Passed';
};
const answer = assertEquals(actual, expected, testCase);
console.log(answer);
/*
Notes:
1. Ask if case sensitive and if whitespaces are an edge case.
2. Ask size of character set.
3. Ask if character set is in ASCII or Unicode.
*/