You are on page 1of 2

1.

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.
Ans:
def containsDuplicate(nums):
num_set = set()
for num in nums:
if num in num_set:
return True
num_set.add(num)
return False

2. You are given an m x n matrix mat and two integers r and c representing the
number of rows and the number of columns of the wanted reshaped matrix. The
reshaped matrix should be filled with all the elements of the original matrix in the
same row- traversing order as they were.
Ans:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
if m * n != r * c:
return mat
ans = [[0] * c for _ in range(r)]
for i in range(m * n):
ans[i // c][i % c] = mat[i // n][i % n]
return ans

3. A phrase is a palindrome if, after converting all uppercase letters into lowercase
letters and removing all non-alphanumeric characters, it reads the same forward
and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Ans:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].lower() != s[j].lower():
return False
else:
i, j = i + 1, j - 1
return True
4. Given two binary strings a and b, return their sum as a binary string.
Ans:
def addBinary(self, a: str, b: str) -> str:
ans = []
carry = 0
i = len(a) - 1
j = len(b) - 1

while i >= 0 or j >= 0 or carry:


if i >= 0:
carry += int(a[i])
i -= 1
if j >= 0:
carry += int(b[j])
j -= 1
ans.append(str(carry % 2))
carry //= 2

return ''.join(ans[::-1])

You might also like