Skip to content

Instantly share code, notes, and snippets.

@muhsalaa
Last active March 2, 2021 03:49
Show Gist options
  • Save muhsalaa/5344270af4671118426259794082bf6d to your computer and use it in GitHub Desktop.
Save muhsalaa/5344270af4671118426259794082bf6d to your computer and use it in GitHub Desktop.
answer of 10 leetcode challenge
/**
* 58. Length of last word
* https://leetcode.com/problems/length-of-last-word/
*/
const lengthOfLastWord = s => {
s = s.trim().split(' ');
const word = s[s.length - 1];
return word.length;
};
/**
* 66. Plus One
* https://leetcode.com/problems/plus-one/
*/
var plusOne = function(digits) {
const res = []
let carriedOver = 0
for (let x = digits.length - 1; x > -1; x--) {
const firstNumber = x === digits.length - 1;
if (carriedOver) {
if (digits[x] + 1 > 9) {
carriedOver = 1
res.unshift(0);
} else {
res.unshift(digits[x] + 1)
carriedOver = 0
}
} else {
if (firstNumber) {
if (digits[x] + 1 > 9) {
carriedOver = 1
res.unshift(0);
} else {
res.unshift(digits[x] + 1)
}
} else {
res.unshift(digits[x])
}
}
}
if (carriedOver) {
if (res[0] === 0) {
res.unshift(1)
} else {
res[0] += 1
}
}
return res
};
/**
* 20. Valid Parentheses
* https://leetcode.com/problems/valid-parentheses
*/
var isValid = function(s) {
let stack = [], mapping = new Map([["}","{"],["]","["],[")","("]])
for (let x = 0; x < s.length; x++) {
if (s[x]=="(" || s[x]=="[" || s[x]=="{") stack.push(s[x])
else {
if (stack.pop() != mapping.get(s[x])) return false
}
}
return !stack.length
};
/**
* 35. Search Insert Position
* https://leetcode.com/problems/search-insert-position/
*/
var searchInsert = function(nums, target) {
const idx = nums.indexOf(target);
if (idx > -1) {return idx}
else if (target < nums[0]) {return 0}
else if (target > nums[nums.length - 1]) {return nums.length}
else {
for (let x = 0; x < nums.length; x++) {
if (target > nums[x] && target < nums[x+1]) {
return x + 1
}
}
}
};
/**
* 136. Single Number
* https://leetcode.com/problems/single-number/
*/
var singleNumber = function(nums) {
const hash = {};
nums.forEach(x => {
hash[x] ? hash[x] += 1 : hash[x] = 1;
})
let y = Object.entries(hash).filter(x => x[1] === 1)[0][0];
return y
};
/**
* 905. Sort Array By Parity
* https://leetcode.com/problems/sort-array-by-parity/
*/
var sortArrayByParity = function(A) {
const even = [], odd = [];
A.forEach(x => x % 2 === 0 ? even.push(x) : odd.push(x));
return [...even, ...odd]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment