Blind 75
Starting today I will be writing writeups for 75 leetcode problems. I will be using python and my main goal is to improve my python.
Contains Duplicate
Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
Example:
Input: nums = [1, 2, 3, 3]
Output: true
Solution: Here we can just use set and len() function to determine whether it contains duplicate or not. Since set preserves one element only in a list it will remove any duplicate and then we can check whether length of set matches that of original list or not. If it does matches the same length then there’s no duplicate. Else it has a duplicate.
a=set(nums)
if len(a)!=len(nums):
return True
else:
return False
Valid Anagram
Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
Example:
Input: s = "racecar", t = "carrace"
Output: true
Solution: Convert string to list, sort the list then check with if list1 in list2. Code:
a=list(s)
b=list(t)
c=sorted(a)
d=sorted(b)
if c in d:
return True
else:
return False
Two Sum
You are 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.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Solution: This one has 2 solution but we will do the more efficient one and its a bit tricky. So what we are going to do is to use a hashmap and we will map the values of list in it with their indexes. Next we will subtract each element of list with target one by one and if the difference exists in hashmap we will return the index of hashmap to that of value with current loop index value.
hashmap={}
for i, j in enumerate(nums):
b=target-nums[i]
if b not in hashmap:
hashmap[j]=i
else:
return i, hashmap[b]