In this code-along, you'll learn how to navigate LeetCode and work with basic data types in JavaScript.
Join us for a live coding session where we'll solve various programming problems using JavaScript.
Developing a systematic approach to problem-solving is crucial for tackling coding challenges. Here's a framework to help you approach any coding problem:
Example: Valid Palindrome
Problem: Determine if a string is a palindrome, considering only alphanumeric characters and ignoring case.
Approach:
function isPalindrome(s) {
// Remove non-alphanumeric and convert to lowercase
const cleanString = s.toLowerCase().replace(/[^a-z0-9]/g, '');
// Check if it reads the same forward and backward
return cleanString === cleanString.split('').reverse().join('');
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
console.log(isPalindrome("race a car")); // false
Example: Two Sum
Problem: Given an array of numbers and a target sum, find two numbers that add up to the target.
Approach:
function twoSum(nums, target) {
// Create a map to store values we've seen and their indices
const map = new Map();
for (let i = 0; i < nums.length; i++) {
// Calculate the complement needed to reach target
const complement = target - nums[i];
// If we've seen the complement before, we found our pair
if (map.has(complement)) {
return [map.get(complement), i];
}
// Store current number and its index
map.set(nums[i], i);
}
return null; // No solution found
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1] (2 + 7 = 9)
Example: FizzBuzz
Problem: Print numbers from 1 to n, but for multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz".
Approach:
function fizzBuzz(n) {
const result = [];
for (let i = 1; i <= n; i++) {
// Check divisibility by both 3 and 5 first
if (i % 3 === 0 && i % 5 === 0) {
result.push("FizzBuzz");
}
// Then check divisibility by 3
else if (i % 3 === 0) {
result.push("Fizz");
}
// Then check divisibility by 5
else if (i % 5 === 0) {
result.push("Buzz");
}
// Otherwise just add the number
else {
result.push(i.toString());
}
}
return result;
}
console.log(fizzBuzz(15));
// [1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz]
When you've solved a problem, always look for ways to optimize:
Problem: Given an integer array, return true if any value appears at least twice, and false if every element is distinct.
Example:
Input: [1,2,3,1] Output: true Input: [1,2,3,4] Output: false
Try to solve this problem on your own first, then check the solution below:
function containsDuplicate(nums) {
// Option 1: Using a Set
return new Set(nums).size !== nums.length;
/* Option 2: Using an object
const seen = {};
for (let num of nums) {
if (seen[num]) return true;
seen[num] = true;
}
return false;
*/
}
console.log(containsDuplicate([1,2,3,1])); // true
console.log(containsDuplicate([1,2,3,4])); // false