Python Leetcode Practice Flashcards
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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# Loop through list
# Check if we’ve seen the num yet
# Create a hash table
# If we haven’t seen the num yet, give it a value of 1
# If we have seen the num return True
# After the loop finishes return False
hash1 = {} for num in nums: if num in hash1: return True else: hash1[num] = 1 return False
Time complexity:
Time - O(n)
Space - O(n)
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
hash1 = {}
hash2 = {}
for letter1 in s:
hash1[letter1] = hash1.get(letter1, 0) + 1
for letter2 in t:
hash2[letter2] = hash2.get(letter2, 0) + 1
return hash1 == hash2
Time complexity:
Time - O(n) *(argument can be made for O(s + t), but we know the strings must be the same length to be valid)
Space - O(n) (O(s + t) for same reason as above)