LeetCode Classics

Solutions to Three Sum, Add Two Numbers, and Longest Substring Without Repeating Characters.

leetcodehash-maplinked-listsliding-windowpython

Two Sum

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        complement = {}
        for i, num in enumerate(nums):
            if (target - num) in complement:
                return complement[target - num], i
            complement[num] = i

Add Two Numbers

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def helper(self, l1, l2, carry):
        if not l1 and not l2:
            if carry != 0:
                return ListNode(carry, None)
            return None

        val1  = l1.val  if l1 else 0
        val2  = l2.val  if l2 else 0
        next1 = l1.next if l1 else None
        next2 = l2.next if l2 else None

        value = (val1 + val2 + carry) % 10
        new_carry = (val1 + val2 + carry) // 10

        node = self.helper(next1, next2, new_carry)
        return ListNode(value, node)


    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        return self.helper(l1, l2, 0)

Longest Substring

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        front, end = 0, 0
        max_length = 0
        while end < len(s):
            sub = s[front:end + 1]
            sub_char_set = set(sub)

            if len(sub) > len(sub_char_set):
                # there is a repeated character
                front += 1
            else:
                end += 1

            if len(sub_char_set) > max_length:
                max_length = len(sub)

        return max_length