Coding Problems Part 1

Joseph Harwood
Jul 19 · 4 min read
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
def two_sum(nums, target)
hash = {}
nums.each_with_index do |num, index|
hash[num] = index
end

nums.each_with_index do |num, index|
diff = target - num
if hash.key?(diff) && hash[diff] != index
return [index, hash[diff]]
end
end
end
var twoSum = function(nums, target) {
let numObject = {};
for (var i = 0; i < nums.length; i++) {
let thisNum = nums[i];
numObject[thisNum] = i;
}
for (var i = 0; i < nums.length; i++) {
let diff = target - nums[i];
if (numObject.hasOwnProperty(diff) && numObject[diff] !== i) {
return [i, numObject[diff]];
}
}
};
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
def reverse(x)
limit = 2147483648
abs = 1
if x < 0
abs = -1
end
n = x.to_s.reverse!.to_i
if n > limit
return 0
else
return n * abs
end
end
var reverse = function(x) {
const limit = 2147483648
const k = x < 0 ? -1 : 1;
// let n = x.toString().split("").reverse().join("")
let n = Number(String(Math.abs(x)).split('').reverse().join(''))
if (n > limit) {
return 0
} else {
return n * k
}
};
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
def first_uniq_char(s)
arr = s.split("")
arr.each_with_index do |ele, i|
if s.index(ele) == s.rindex(ele)
return i
end
end
return -1
end
var firstUniqChar = function(s) {
for(let i = 0; i < s.length; i++){
if (s.indexOf(s[i]) === s.lastIndexOf(s[i])){
return i;
}
}
return -1;
};
// bbaaa => baaab true
// wkjqq => false
// ffeeaaf => feafaef true
function checkPalindrome(input) {

counter = {}
for (let i = 0; i < input.length; i++) {
if (counter[input[i]]) {
counter[input[i]] += 1
} else {
counter[input[i]] = 1
}
}

let oddGuy = 0
Object.keys(counter).forEach( i => {
if (counter[i] % 2 === 1) {
oddGuy += 1
}
})

if (oddGuy > 1){
return false
} else {
return true
}
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade