Writing
-
Leetcode: String in String
Continue readingA classic find the
needlein thehaystackproblem. The task is to find if a string is contained within another string and return the index of the first position. If the string is not contained return-1and if theneedleis empty, return0. -
Leetcode: Merge two lists
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: root = ListNode() current = root while list1 is not None and list2 is not None: if list1.val < list2.val: current.next = ListNode(list1.val) current = current.next list1 = list1.next else: current.next = ListNode(list2.val) current = current.next list2 = list2.next if list1 is not None: current.next = list1 if list2 is not None: current.next = list2 return root.nextResults
Runtime: 34 ms, faster than 97.81% of Python3 online submissions for Merge Two Sorted Lists.
Memory Usage: 13.9 MB, less than 79.56% of Python3 online submissions for Merge Two Sorted Lists.
-
Leetcode: All possible subsets
Continue readingA subset of a list with the elements
{a,b,c}is{a,b}. The task is to find all possible subsets. Sets in programming languages are usually not ordered. Therefore, the set{a,b,c}is equivalent to{b,c,a}.The idea for the solution is a nested
for-loop that iterates over the results again and again, starting with one empty ([]) result. -
Leetcode: Permutations
Continue readingThe goal of this task is to find all possible permutations of numbers in a list. For example,
[1,2,3]can become[[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]. Mathematically, the number of possible permutations without using duplicates isn!wherenis the number of unique elements in the list.This problem can best be solved by using backtracing and recursion. The general idea is to put all possible digits in the beginning and then cut off the rest of the list and repeat the first step. Later, the list is assembled. The algorithm stops if there is only one item in the list because the only possible permutation is with itself. The other special case that needs to be handled is the empty list which must return the empty list itself.
-
How to add Devise to Rails
Great tutorial how to use Devise with Rails 7 and Turbo: Youtube.