Hashmap

Leetcode 15 Three Sum

July 14, 2024
Hashmap

3. Longest Substring Without Repeating Characters # Given a string s, find the length of the longest substring without repeating characters.

Leetcode 1 Two sum, Leetcode 454 four sum

July 9, 2024
Hashmap

Leetcode 1 two sum # func twoSum(nums []int, target int) []int { m := map[int]int{} for i, v := range nums{ another := target - v if index, found := m[another]; found{ return []int{i,index} } m[v]=i } return nil } Leetcode 454. 4Sum II # Problem Description # Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: ...

Leetcode 15 Three Sum, Leetcode 16 3Sum Closest, Leetcode 18 four sum

July 9, 2024
Hashmap

Leetcode 15 three sum # Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. to help understand it better. The key challenge here is to remove duplicates in results Why not use hashmap solution as two sums? ...

Leetcode 202 happy number

July 9, 2024
Hashmap

Leetcode 202 Happy Number # A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not. ...

Leetcode 242 Valid Anagram

July 9, 2024
Hashmap

Leetcode 242: Valid Anagram # In this post, we will discuss how to solve the popular LeetCode problem: “Valid Anagram”. This problem requires us to determine if two given strings are anagrams of each other. Two strings are anagrams if they contain the same characters with the same frequencies. Problem Statement # Given two strings s and t, write a function isAnagram(s string, t string) bool that returns true if t is an anagram of s, and false otherwise. ...

Leetcode 383 ransom note

July 9, 2024
Hashmap

Leetcode 383 ransom note # Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. Answer: I have learnt that we can early return false if letterCount[char-'a'] < 0 func canConstruct(ransomNote string, magazine string) bool { // Create an array to count the occurrences of each letter in the magazine letterCount := [26]int{} for _, char := range magazine { letterCount[char-'a']++ } // Check if the ransom note can be constructed from the magazine for _, char := range ransomNote { letterCount[char-'a']-- if letterCount[char-'a'] < 0 { return false } } return true }