<jupyter_start><jupyter_text>1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.Example:Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].<jupyter_code>class Solution:
    def twoSum(self, nums, target):
        
        
        h = {}                            # strore numbers that have already been seen
        
        for i , num in enumerate(nums):   # get index and numbers of list
            
            n = target - num              # calculate possible secondary number
            
            if n not in h:                # check to see if secondary number has already been seen
                
                h[num] = i                # if it hasn't add it and index to the list and move on
                
            else:                         # if it has already been seen we have the two numbers we need
                return [h[n], i]          # return index of first number that has already been seen and second number<jupyter_output><empty_output><jupyter_text>7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer.Examples:Input: 123Output: 321Input: -123Output: -321Input: 120Output: 21Note:Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.<jupyter_code>class Solution:
    def reverse(self, x: int) -> int:
        
        
        if x > 0:                              # for positive numbers  
            a =  int(str(x)[::-1])             # reverse slice every character as a string then convert to int
        
        if x <=0:                              # for negative numbers or 0  
            a = -1 * int(str(x*-1)[::-1])      # same but change to positive and then after back to negative
        
        
                                               # for 32 bit overflow  
        mina = -2**31  
        maxa = 2**31 - 1  
        
        if a not in range(mina, maxa):         # if outside of exclusive range then return 0
            return 0        
        else:  
            return a                           # otherwise return a<jupyter_output><empty_output><jupyter_text>9. Palindrome Number Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.Example 1:Input: 121Output: trueExample 2:Input: -121Output: falseExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.Example 3:Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome.Follow up:Coud you solve it without converting the integer to a string?<jupyter_code>class Solution:
    def isPalindrome(self, x: int) -> bool:
        

        test = 0
        temp = x
        
        while(x>0):                # run while positive... palindromes can't be negative
            last = x%10            # get the last digit of number by using mod 10 (pop it out)
            test = test*10 + last  # move everything over by one decimal place and add the last digit to test number
            x = x//10              # remove the last digit from number by dividing by 10 with no remainder
        
        if temp == test:           # if test matches temp it's a palindrome
            return True
        
        else:
            return False           # if no match or number is negative then not a palidrome<jupyter_output><empty_output><jupyter_text>13. Roman to Integer Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.Example 1:Input: "III"Output: 3Example 2:Input: "IV"Output: 4Example 3:Input: "IX"Output: 9Example 4:Input: "LVIII"Output: 58Explanation: L = 50, V= 5, III = 3.Example 5:Input: "MCMXCIV"Output: 1994Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.<jupyter_code>class Solution:
    def romanToInt(self, s: str) -> int:
        
        roman_to_int = {                             # dictionary of values
            'I' : 1,
            'V' : 5,
            'X' : 10,
            'L' : 50,
            'C' : 100,
            'D' : 500,
            'M' : 1000
        }
        
        result = 0                                  # initialize values
        prev_value = 0
        
        for digit in s:                             # loop through input digits
            
            value = roman_to_int[digit]             # select the corresponding value
            result += value                         # add value to result 
            
            if value > prev_value:
                                                    # if preceding roman nummber is smaller
                result -= 2 * prev_value            # we need to undo the previous addition
                                                    # and substract the preceding roman char
                                                    # from the current one, i.e. we need to
                                                    # substract twice the previous roman char

            prev_value = value                      # set previous and repeat
        
        return result<jupyter_output><empty_output><jupyter_text>14. Longest Common Prefix 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 "".Example 1:Input: ["flower","flow","flight"]Output: "fl"Example 2:Input: ["dog","racecar","car"]Output: ""Explanation: There is no common prefix among the input strings.Note:All given inputs are in lowercase letters a-z.<jupyter_code>class Solution:
    def longestCommonPrefix(self, strs):

    
    
        if len(strs)==0:                    # if there are no words passed return nothing   
            return ""

        if len(strs)==1:                    # if there is only one word return that word
            return strs[0] 

        cp = ''                              # instantiate a common prefix string

        l = [len(st) for st in strs]         # get lengths for each word 
        
        for i in range(min(l)):              # loop from first letter to length of shortest word
            tmp = [s[i] for s in strs]       # get i-th letter from each word
            
            if min(tmp) == max(tmp):         # check if all i-th letters are the same
                cp = cp + tmp[0]             # add that i-th letter to common prefix string
                
            else:                            # if i-th letters dont match return the common prefix string
                return cp
            
        return cp<jupyter_output><empty_output><jupyter_text>20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.An input string is valid if:Open brackets must be closed by the same type of brackets.Open brackets must be closed in the correct order.Note that an empty string is also considered valid.Example 1:Input: "()"Output: trueExample 2:Input: "()[]{}"Output: trueExample 3:Input: "(]"Output: falseExample 4:Input: "([)]"Output: falseExample 5:Input: "{[]}"Output: true<jupyter_code>class Solution(object):
    def isValid(self, s):
        
        """
        :type s: str
        :rtype: bool
        """

        # The stack to keep track of opening brackets.
        stack = []

        # Hash map for keeping track of mappings. This keeps the code very clean.
        # Also makes adding more types of parenthesis easier
        mapping = {")": "(", "}": "{", "]": "["}

        # For every bracket in the expression.
        for char in s:

            # If the character is a closing bracket
            if char in mapping:

                # Pop the topmost element from the stack, if it is non empty
                # Otherwise assign a dummy value of '#' to the top_element variable
                top_element = stack.pop() if stack else '#'

                # The mapping for the opening bracket in our hash and the top
                # element of the stack don't match, return False
                if mapping[char] != top_element:
                    return False
            else:
                # We have an opening bracket, simply push it onto the stack.
                stack.append(char)

        # In the end, if the stack is empty, then we have a valid expression.
        # The stack won't be empty for cases like ((()
        return not stack
class Solution(object):
    def isValid(self, s):
        while "()" in s or "{}" in s or '[]' in s:
            s = s.replace("()", "").replace('{}', "").replace('[]', "")
        return s == ''
    
    
# this is like eating the apple from the inside - out
# first eat the core, then the insides, then the skin
# if there is nothing left after getting rid of open-closed pairs then return true<jupyter_output><empty_output><jupyter_text>21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.Example:Input: 1->2->4, 1->3->4Output: 1->1->2->3->4->4<jupyter_code># Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        
        dummy = curr = ListNode(-1)     # set current place to a dummy node with smallest value of -1
        
        while l1 or l2:                 # while either of the two lists exist
            if l1 and l2:               # if both lists exist
                
                if l1.val < l2.val:     # if l1 has smaller value
                    curr.next = l1      # append l1's smaller value to the current list using .next
                    l1 = l1.next        # move l1's node over to the next smallest node
                    curr = curr.next    # the new current value is l1's last value
                    
                else:                   # else if l2 has a smaller value
                    curr.next = l2      # append l2's smaller value to the current list using .next
                    l2 = l2.next        # move l2's node over to the next smallest node
                    curr = curr.next    # the new current value is l2's last value
                    
            elif l1 or l2:                       # if only one list still exists
                curr.next = l1 if l1 else l2     # then append remaining list values to current list
                break                            # break out of loop since it's finished
                
        return dummy.next               # return list besides the first dummy node of -1<jupyter_output><empty_output><jupyter_text>26. Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.Example 1:Given nums = [1,1,2],Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.It doesn't matter what you leave beyond the returned length.Example 2:Given nums = [0,0,1,1,1,2,2,3,3,4],Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.It doesn't matter what values are set beyond the returned length.Clarification:Confused why the returned value is an integer but your answer is an array?Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.<jupyter_code>class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:


        nums[:] = sorted(set(nums))          # slice assignment to a sorted set (distinct values) of the numbers
        return len(nums)                     # return the length of the list<jupyter_output><empty_output><jupyter_text>27. Remove Element Given an array nums and a value val, remove all instances of that value in-place and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.The order of elements can be changed. It doesn't matter what you leave beyond the new length.Example 1:Given nums = [3,2,2,3], val = 3,Your function should return length = 2, with the first two elements of nums being 2.It doesn't matter what you leave beyond the returned length.Example 2:Given nums = [0,1,2,2,3,0,4,2], val = 2,Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.Note that the order of those five elements can be arbitrary.It doesn't matter what values are set beyond the returned length.<jupyter_code>class Solution:
    def removeElement(self, nums, val):
        
        
        start, end = 0, len(nums) - 1                # instantiate start at 0 and end on second to last value
        
        while start <= end:                          # while loop through values
            
            if nums[start] == val:
                nums[start], nums[end], end = nums[end], nums[start], end - 1
                
                # if we hit the target value then swap it from the right most item and decrement length 
                
            else:
                start +=1         # increment start and move current value to the right
                
        return start              # return list of values<jupyter_output><empty_output><jupyter_text>28. Implement strStr() Implement strStr().Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.Example 1:Input: haystack = "hello", needle = "ll"Output: 2Example 2:Input: haystack = "aaaaa", needle = "bba"Output: -1<jupyter_code>class Solution:
def strStr(self, haystack: 'str', needle: 'str') -> 'int':
    
    for i in range(0, len(haystack) - len(needle) + 1):      # loop through characters until the length of the last characters is less than the needle, add 1 to make the loop executable
        if haystack[i:i+len(needle)] == needle:              # if character string in haystack matches needle
            return i                                         # return index of haystack value
    
    return -1                                                # otherwise return -1<jupyter_output><empty_output><jupyter_text>35. Search Insert Position Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.You may assume no duplicates in the array.Example 1:Input: [1,3,5,6], 5Output: 2Example 2:Input: [1,3,5,6], 2Output: 1Example 3:Input: [1,3,5,6], 7Output: 4Example 4:Input: [1,3,5,6], 0Output: 0<jupyter_code>class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        
        
        if not nums:                           # if nothing is passed return 0
            return 0
        
        for i, num in enumerate(nums):         # loop through index and number in nums     
            if num >= target:                  # if current number is >= target return index
                return i
        
        return len(nums)                        # return len of nums
import bisect                                                          # using bisect library

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        return bisect.bisect_left(nums, target)<jupyter_output><empty_output><jupyter_text>38. Count and Say The count-and-say sequence is the sequence of integers with the first five terms as following:1.     12.     113.     214.     12115.     1112211 is read off as "one 1" or 11.11 is read off as "two 1s" or 21.21 is read off as "one 2, then one 1" or 1211.Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.Note: Each term of the sequence of integers will be represented as a string. Example 1:Input: 1Output: "1"Explanation: This is the base case.Example 2:Input: 4Output: "1211"Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".<jupyter_code>class Solution:
    def countAndSay(self, n: int) -> str:
        
        s = '1'                                          # seed with value of 1
        
        for _ in range(n-1):                             # loop through all but last element in range of n  (since we seeded with 1)
            
            tmp, count = [], 1                           # instantiate temporary list and current count of 1
            
            for i in range(1, len(s)):                   # loop though s
                
                if s[i-1] == s[i]:                       # if last element in s is same as current
                    count += 1                           # increment count by 1 to 2
                    
                else:
                    tmp.extend([str(count), s[i-1]])     # else use extend to append count and previous element to temporary list
                    count = 1                            # reset the count equal to 1
                    
            tmp.extend([str(count), s[-1]])              #  use extend to append count and last element to temporary list
            s = ''.join(tmp)                             # join all elemnts in temporary list as s
            
        return s                                         # return joined list s<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07214113199621967, 'fraction_numerical': 0.02236690118660086, 'mean_word_length': 1.861198738170347, 'pattern_counts': {'":': 3, '<': 52, '<?xml version=': 0, '>': 72, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 31, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '84671', 'license': 'MIT', 'n_tokens_mistral': 5218, 'n_tokens_neox': 4794, 'n_words': 2283, 'path': 'LeetCode.ipynb', 'repo_name': 'sam-brady/leetcode', 'size': '19046'}