CodePath Data Structure Patterns

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Dictionaries - 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.

1) Initialize a Frequency Dictionary: Create an empty dictionary to keep track of the count of each character in the magazine. 2) Build the Frequency Dictionary from magazine:Iterate over each character in the magazine. -> For each character, increment its count in the dictionary if it already exists; otherwise, add it to the dictionary with a count of 1. 3) Check Each Character in ransomNote: Iterate over each character in the ransomNote. - -> For each character, check if it exists in the frequency dictionary and has a count greater than 0. -> If it exists and the count is greater than 0, decrement the count by 1. -> If it does not exist or the count is 0, return false because the ransomNote cannot be constructed from the magazine. 4) Return true: If all characters in ransomNote are successfully matched and decremented in the dictionary, return true.

Lists - Contains Duplicate Implementation

class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ seen = set() for num in nums: if num in seen: return True seen.add(num) return False

Lists - Remove Duplicates from Sorted Array and Count Unique Elements Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

1) Check for Non-Empty List: Ensure the list is not empty. If it is empty, return 0. 2) Initialize Next Unique Index Tracker: Create a variable to keep track of the index where the next unique element will be placed. Start this variable at 0. 3) Iterate Through the List: Traverse the list using a loop, typically using a traversal variable ranging from 1 to the length of the list. 4) Check for Uniqueness: Compare the element at the current traversal index with the element at the unique index tracker. 5) Update Next Unique Index if Element is Unique: If the element at the current traversal index is not equal to the element at the unique index tracker, it's a new unique element. 6) Update Next Unique Index Tracker and Array: Increment the unique index tracker by one so the next unique element will be placed after the current element. Set the element at the unique index tracker equal to the element at the current traversal index. 7) Return Count of Unique Elements: After traversing the list, return the next index tracker + 1 to find the count of unique elements. The next index tracker represents the index where the next unique element would be placed, and adding 1 gives the total count of unique elements.

Lists: Two Sum Given an array of integers nums and an integer target, 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. You can return the answer in any order.

1) Create a Dictionary: Start by creating an empty dictionary. This dictionary will store the numbers we've seen so far along with their indices in the list. 2) Iterate Through the List: Go through each number in the list one by one. 3) Check for Complement: For each number, calculate its complement (the value needed to reach the target sum) by subtracting it from the target. 4) Check if Complement Exists: Check if the complement exists in the dictionary. If it does, it means we've found a pair of numbers that sum up to the target. We return the indices of the current number and the complement from the dictionary. 5) Store Number in Dictionary: If the complement doesn't exist in the dictionary, it means we haven't seen the complement's pair yet. So, we store the current number along with its index in the dictionary for future reference. 6) Repeat Until End of List: Keep iterating through the list, repeating steps 3 to 5, until we either find a pair that sums up to the target or until we reach the end of the list. 7) Return Indices or None: If we find a pair that sums up to the target, we return the indices of the two numbers. If we reach the end of the list without finding such a pair, we return None to indicate that no such pair exists.

Lists - Best Time to Buy and Sell Stock You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

1) Initialization: Initialize max_profit to 0 and min_price to positive infinity. 2) Iterate through prices: Loop through each price in the list of stock prices. 3) Update min_price to be the minimum of its current value and the current price. 4) Update max_profit to be the maximum of its current value and the difference between the current price and min_price. 5) Return maximum profit: After iterating through all prices, return max_profit, which represents the maximum profit achievable.

Lists - Remove Element Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things: - Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. - Return k.

1) Initialization: We initialize k to 0. This variable k will keep track of the position where the next non-val element should be placed. 2) Iteration: We iterate through each element of the array using the index i. 3) Condition Check: For each element nums[i], we check if it is not equal to val. 4) Element Assignment: If nums[i] is not equal to val, we assign nums[i] to nums[k]. This means we are moving the non-val element to the position k. 5) Increment k: After placing the non-val element at position k, we increment k to prepare for the next non-val element.

Lists - Merge Sorted Array You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

1) Initialization: We start with two pointers, p1 and p2, positioned at the end of nums1 and nums2 respectively. We also have another pointer p pointing to the last position of the merged array (nums1). 2) Comparison and Placement: We compare the elements at nums1[p1] and nums2[p2]. The larger element gets placed at position p in nums1. Then, we decrement the respective pointer (p1 or p2) and move p backward to the next position. 3) Repeat Until Exhaustion: We repeat this process until we have compared all elements in both arrays. This ensures that all elements are merged in the correct order. 4) Finishing Up: After exiting the loop, if there are still elements left in nums2, we simply copy them to the beginning of nums1.

Lists - Contains Duplicate Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

1) Initialize an Empty Set: Create an empty set called seen to keep track of elements that have been encountered so far. 2) Iterate Through the Array: For each element num in the array nums, do the following: 3) Check for Duplicates: -> Check if num is already in the seen set.If num is found in the seen set, it means it's a duplicate, so return True immediately. -> If num is not found in the seen set, proceed to the next step. 4) Add Element to the Set: Add num to the seen set to mark it as encountered. 5) Return False: If the loop completes without finding any duplicates, return False.

Lists - Remove Element Implementation

class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ k = 0 #counter for number of elements not equal to val for i in range(len(nums)): # iterate over range of length of nums: if nums[i] != val: # if current element is not equal to val nums[k] = nums[i] # move non-val element to front k+=1 # increment counter return k # return the count of elements not equal to val

Lists - Best Time to Buy and Sell Stock Implementation

class Solution: def maxProfit(self, prices: List[int]) -> int: max_profit = 0 min_price = float('inf') for price in prices: min_price = min(price, min_price) max_profit = max(max_profit, price - min_price) return max_profit

Dictionaries - Ransom Note Implementation

def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ freq_dict = {} for char in magazine: if char in freq_dict: freq_dict[char] += 1 else: freq_dict[char] = 1 for char in ransomNote: if char in freq_dict and freq_dict[char] > 0: freq_dict[char] -= 1 else: return False return True

Lists - Remove Duplicates from Sorted Array and Count Unique Elements Implementation

def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 unique_index = 0 for current_index in range(1, len(nums)): if nums[current_index] != nums[unique_index]: unique_index+=1 nums[unique_index] = nums[current_index] return unique_index + 1

Lists - Two Sum Implementation

def two_sum(nums, target): indices_dict = {} for i in range(len(nums)): complement = target - nums[i] if complement in indices_dict: return [ indices_dict[complement], i ] indices_dict [ nums[ i ] ] = i return none

Lists - Merge Sorted Array Implementation

if nums1 is None: return None p1 = m - 1 p2 = n - 1 p = m + n - 1 while p1 >= 0 and p2 >= 0: if nums1[p1] > nums2[p2]: nums1[p] = nums1[p1] p1 -= 1 else: nums1[p] = nums2[p2] p2 -= 1 p -= 1 # If there are remaining elements in nums2, copy them to nums1 while p2 >= 0: nums1[p] = nums2[p2] p2 -= 1 p -= 1


Ensembles d'études connexes

Chapter 43: Hematological or Immunological Pediatric

View Set

data analysis chapter 11 study guide

View Set

Biology, Light Independent Reactions in Photosynthesis

View Set

NUTR 251 - Smartbook Ch. 13 - Water-Soluble Vitamins

View Set

Outline 15: Leg, Knee, and Popliteal Fossa

View Set