/images/pfp.png

Leetcode 11: Longest common prefix

Problem statement: Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

First, let’s set the obvious limitation of our result: it is either the empty string or our result is at most equal to the smallest string in the given array. With this in mind, we get a first obvious solution, check all substrings of all of the given strings (in ascending order of length) up until the point where we find a mismatch between them. The previously observed substring will then correspond to the longest common prefix.

Leetcode 10: Two sum

Problem statement: given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j. You may assume that every input has exactly one pair of indices i and j that satisfy the condition. Return the answer with the smaller index first.

Let’s do some thinking. The obvious answer would be to have two nested loops and iterate over nums while checking when the sum equals target, but that’s too easy so surely there must be a better way. We can treat our condition as we would any other equation and do:

Leetcode 9: Valid anagram

Problem statement: 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.

Not much to say here, this is immediate using Counters, just create one for each string and compare them directly with ==.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import unittest
from collections import Counter
from dataclasses import dataclass

class AnagramChecker():
    def check(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)

class TestAnagramChecker(unittest.TestCase):
    def test_check(self):
        @dataclass
        class TestCase:
            name: str
            s: str
            t: str
            expected: bool

        test_cases = [
            TestCase(name="not an anagram", s="racecar", t="carrace", expected=True),
            TestCase(name="is an anagram", s="mouse", t="house", expected=False),
            TestCase(name="works for empty string", s="", t="", expected=True)
        ]

        checker = AnagramChecker()
        for tc in test_cases:
            res = checker.check(tc.s, tc.t)
            self.assertEqual(tc.expected, res, f"[{tc.name}] - expected {tc.expected} but got {res}")


if __name__ == "__main__":
    unittest.main()

Leetcode 8: Contains duplicate

Problem statement: given an integer array nums, return true if any value appears more than once in the array, otherwise return false.

We have several ways we can solve this. We can use a standard Python dictionary, where we iteratively store the integers of the array as keys associated with any value and, in case we find a key that already exists, we can adequately flag the array as containing duplicates. We can also use a Counter, give it he full array and compare the total count with the number of keys in the Counter: if these differ, then there are duplicates. Similarly, we can create a set from the array and, in case the set has less values than the array, it contains duplicates. Finally, we can sort the array and iterate over it, checking the current number against the one that follows it and, in case these match, then there is a duplicate. This last option is the least efficient of the bunch since it requires sorting the array.

Leetcode 7: Concatenation of array

Problem statement: given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i+n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums array. Return the array ans.

I am sure that this exercise is challenging in some programming languages. However, python is not one of them, since we can simply use + to concatenate two arrays.

Leetcode 6: String rotation

Problem statement: Assume you have a method which checks if one word is a substring of another. Given two strings, write code to check if the latter is a rotation of the former using only one call to the aforementioned method.

This one is super straightforward once you know the trick. If you take the original string and concatenate it with itself, then all of the string’s rotations will be included in the concatenation. Thus, it will then suffice to simply use the method to check if the word is a substring of another and, if it is, then it must be a rotation. Note that we must check the length because rotation preserves the length.