strings Flashcards

1
Q
  1. Group Anagrams
    Given an array of strings strs, group the anagrams together. You can return the answer in any order.

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.

A

def findAnagram(strings):

    #example string Input: strs = ["eat","tea","tan","ate","nat","bat"]
    #Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
anagram = {}

for words in strings:
    sortedword = ''.join(sorted(words))

    if sortedword in anagram:
        anagram[sortedword].append(words)
    else:
        anagram[sortedword] = [words]
return list(anagram.values())

strings = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
print(findAnagram(strings))

Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. Word Pattern
    Given a pattern and a string s, find if s follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

Input: pattern = “abba”, s = “dog cat cat dog”
Output: true

A
class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        splitA = s.split()
        return list(map(pattern.index, pattern)) == list(map(splitA.index, splitA))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. Reverse String solution 1

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

A
class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
    left, right = 0, len(s)- 1

    while left < right:

        s[left], s[right] = s[right], s[left]

        left, right = left + 1, right - 1 return string
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

A
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = collections.Counter(s)
        for idx, char in enumerate(s):
            if count[char] == 1:
                return idx
    return -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. To Lower Case

Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.

A
class Solution(object):
    def toLowerCase(self, s):
        """
        :type s: str
        :rtype: str
        """
    return s.lower()
solution 2:
    def toLowerCase(self, s):
        """
        :type s: str
        :rtype: str
        """
    upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lower = "abcdefghijklmnopqrstuvwxyz"
    h = dict(zip(upper, lower))

    return ''.join([h[x] if x in h else x for x in s])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  1. Maximum Number of Balloons

Given a string text, you want to use the characters of text to form as many instances of the word “balloon” as possible.

You can use each character in text at most once. Return the maximum number of instances that can be formed.

example
text = “nlaebolko”

A

from collections import Counter

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        c = Counter(text)
        return min(c['a'], c['b'], c['l']//2, c['o']//2, c['n'])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How To Convert Python String To Array?

example string = ‘hello’

A

example1
str = “MillieB11”
arr = list(str)
print(arr)

output = [‘M’, ‘i’, ‘l’, ‘l’, ‘i’, ‘e’, ‘B’, ‘1’, ‘1’]

example 2
str = “Millie Bobby Brown is Enola Holmes”
arr = str.split()
print(arr)

[‘Millie’, ‘Bobby’, ‘Brown’, ‘is’, ‘Enola’, ‘Holmes’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to sort a string without separating the characters?

A

example1

sortedwords = ‘‘.join(sorted(‘word’)

print sorted words —> dorw

example two:

print(sorted(‘aet’)) —> [‘a’, ‘e’, ‘t’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to stow dictionary keys and their count of a string?

A

using collections.Counter()

from collections import Counter

example
s = ‘leetcode’

count = Counter(s)
result –> Counter({‘e’: 3, ‘l’: 1, ‘t’: 1, ‘c’: 1, ‘o’: 1, ‘d’: 1})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Palindrome check (algoexpert)

write a function that takes in a non-empty string that returns a boolean representing whether a string is a palindrome.

a palindrome is referred to as a string that is written the same forward as backward

eg. string = ‘abcdcba’

A
def isPalindrome(string):
    # Write your code here.
    return (string == string[::-1])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

what does this % operator sign mean in python?

A

Modulus - remainder of the division of left operand by the right

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

what does this // operator sign mean in python?

A

Floor division - division that results into whole number adjusted to the left in the number line

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Caesar Cipher Encryptor (Algoexpert)

Given a non-empty string of lowercase letters and a non-negative integer representing a key, write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet, where k is the key.

A
def caesarCipherEncryptor(string, key):
    # Write your code here.
    #i want to use the 26 scale.so i will change everything to upper
	string = string.upper()
key = key%26
	#let's keep track of the char and their corresponding numbers
	#let's also keep track of the new string
	newString = []
	for char in string:
		numberChar = ord(char)
		#let's make the shift in the number
		newNumber = numberChar + key
		if newNumber <= 90:
			newChar = chr(newNumber)
			newString.append(newChar)
		else:
			newChar = chr(newNumber+64-90)
			newString.append(newChar)
	return ''.join(newString).lower()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you change a string to upper case?

A

string.upper()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you change a string to lower case?

A

string.lower()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to change an array of characters for example [‘C’, ‘D’, ‘E’, ‘F’] into a string ‘CDEF’

A

string1 = [‘C’, ‘D’, ‘E’, ‘F’]

print(‘‘.join(string1))

17
Q

reverse integer consider negative numbers

A
def solution (x):
#     if x is a number and it has negative numbers
    string = str(x)
if string[0] == '-':
    return int('-'+ string[:0:-1])
else:
    return int(string[::-1])
18
Q

Average words length

for a given sentence return the average word length
remove all punctuation first

example

sentence = ‘Hi all, my name is Tom… I am originally from Australia’

A

def averageWord(sentence):

for p in ':;.,!?/':

    sentence = sentence.replace(p, "")
    words = sentence.split()
    return round(sum(len(word) for word in words)/len(words),2)

sentence = “hi all! my name is …..Felly. I am happy to see you”

print(averageWord(sentence))

19
Q

Move zeroes to the end

example : nums = [0, 1, 2, 4, 0, 5, 0]

A

def moveZeroes(nums):

for i in nums:
    if 0 in nums:
        nums.remove(0)
        nums.append(0)

return nums
20
Q
  1. Valid Palindrome
    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.

A
class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
    result = "".join(ch for ch in s if ch.isalnum()).lower()
    return result == result[::-1]
21
Q
  1. Valid Anagram

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.

A
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        # def validAnagram (s,t):
    return sorted(s) == sorted(t)