Coding questions Flashcards
1
Q
Reverse words in sentence
in:
“Let’s take LeetCode contest”
Out:
“s’teL ekat edoCteeL tsetnoc”
A
def reverseWords(self, s):
“””
:type s: str
:rtype: str
“””
words = s.split() words = [word[::-1] for word in words] return " ".join(words)
2
Q
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.
A
- The trick - hashing, use current_num + x = target,
use map to store previously encountered values (two 4-loops would be time O(n2) and space O(1). With map both time and space is O(n).)
diffs = dict()
for i, num in enumerate(nums):
look_for = target - num
if look_for in diffs.keys():
return i, diffs[look_for]
diffs[num] = i
3
Q
Whats the syntax of declaring an empty tuple, list, etc
A
two pointers:
left, right = 0, len(ary) - 1 while left < right: if ary[right] is 0: ary[:0] = [ary.pop(right)] left += 1 else: right -= 1 return ary
4
Q
Given an integer x, return true if x is a
palindrome
, and false otherwise.
A