Today, I tackled two foundational and frequently asked coding interview problems β Two Sum and Palindrome Number β both great for strengthening your problem-solving skills in JavaScript. I focused on writing clean code, understanding constraints, dry running inputs, and thinking through edge cases.
β Problem 1: Two Sum
π Problem Statement:
Given an array of integers
nums
and an integertarget
, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.
Return the answer in any order.
Example
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
// Explanation: Because nums[0] + nums[1] == 9
β JavaScript Code:
var twoSum = function(nums, target) {
if(nums.length < 2) return null;
for(let i = 0; i < nums.length; i++) {
for(let j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
// Testing the function
console.log('First Answer', twoSum([2, 7, 11, 15], 9)); // [0,1]
console.log('Second Answer', twoSum([3, 2, 4], 6)); // [1,2]
console.log('Third Answer', twoSum([3, 3], 6)); // [0,1]
console.log('Fourth Answer', twoSum([3, 2, 3], 6)); // [0,2]
β Problem 2: Palindrome Number
π Problem Statement:
- Given an integer
x
, returntrue
ifx
is a palindrome, andfalse
otherwise.
Example
Input: x = 121
Output: true
Input: x = -121
Output: false
Input: x = 10
Output: false
β JavaScript Code:
var isPalindrome = function(x) {
let ActualValue = x.toString();
let ReverseValue = x.toString().split('').reverse().join('');
console.log(ActualValue, ReverseValue);
return ActualValue === ReverseValue;
};
// Testing the function
console.log(isPalindrome(121)); // true
console.log(isPalindrome(-121)); // false
console.log(isPalindrome(10)); // false
π What I Learned Today
π§ 1. Dry Run Is Powerful
Manually walking through the logic before coding saved time and reduced bugs.
π§© 2. Think About Edge Cases
I considered inputs like:
- Arrays with one element
- Duplicate values
- Negative integers
π§Ό 3. Clean Code Matters
Writing clean and readable code helps future-proof my logic and reduces confusion.
βοΈ 4. Brute Force is OK at First
Start with what's simple and correct. Optimization can come later once the logic is solid.
βοΈ 5. "Copy & Think" Habit
Instead of copy-pasting code, I pause to understand why it works. This makes learning deeper and longer-lasting.
Top comments (0)