Skip to content

Instantly share code, notes, and snippets.

View codecakes's full-sized avatar
💭
I may be slow to respond.

codecakes codecakes

💭
I may be slow to respond.
View GitHub Profile
@codecakes
codecakes / max_ones_with_replacement_zero.py
Created September 27, 2022 13:10
Max Consecutive Ones with 0 replacement
"""
Given a binary array nums and an integer k,
return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
"""
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left = 0
zero_count = 0
@codecakes
codecakes / longest_repeating_subsequence.kt
Created September 26, 2022 13:57
Longest Repeating Character with Replacement
// This isn't the most optimal kotlin code. but it is one that solves all cases.
class Solution {
fun characterReplacement(s: String, k: Int): Int {
val n = s.length
val maxCharMap = mutableMapOf<Char, Int>();
var left = 0
var maxCount = Float.NEGATIVE_INFINITY.toInt()
var newMax = maxCount
@codecakes
codecakes / factorial_runtimes.py
Created September 21, 2022 19:32
playing with recursive, linear and simple factorial runtimes
# -*- coding: utf-8 -*-
import functools
import time
def fact(n):
if n < 2: return 1
# this will still produce stack returns to return back.
return n * fact(n-1)
@codecakes
codecakes / set_covering_greedy.py
Created September 20, 2022 23:28
The problem of set of combinations using approximation
from typing import Dict
def find_optimal_stations():
places_to_cover = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"])
hashset_places: Dict[set] = {
"kone": set(("id", "nv", "uv")),
"ktwo": set(["wa", "id", "mt"]),
"k3": set(["or", "nv", "ca"]),
"k4": set(["nv", "ut"]),
from typing import Optional, List
from collections import defaultdict
from itertools import groupby
def grouped_anagram(anagram_arr: List[str]) -> List[List[str]]:
w_group = defaultdict(list)
for key_sum, word in groupby(anagram_arr, lambda w: sum(map(ord, w))):
w_group[key_sum] += list(word)
return list(w_group.values())
@codecakes
codecakes / happy_number.py
Created September 11, 2022 11:05
A number is happy if recursively all the sums of squares of inidividual digits equal 1 otherwise its false if numbers keep repeating.
def happy_number(x: int, result=0, seen: Optional[set] = None) -> bool:
seen = seen or set()
num_to_sqr, new_num = ((x%10)**2 + result), x//10
# print(f"1st num_to_sqr={num_to_sqr} new_num={new_num}")
seen.add(num_to_sqr)
# print(f"seen={seen}")
if new_num:
res = happy_number(new_num, num_to_sqr, seen)
@codecakes
codecakes / odd_number_arr.py
Created September 11, 2022 09:48
Single out the the number present in uneven count in an array
import functools as fnctl
print(fnctl.reduce(lambda x, y: x^y, (4,1,2,1,2)))
@codecakes
codecakes / first_missing_positive_num.py
Created September 9, 2022 13:15
First missing positive number in an array
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
# filter non negative, new size n
arr = sorted(filter(lambda x: x > 0, nums))
count = len(arr)
# filter all num <= n to a hash set and keep new count, count.
arr = filter(lambda x: x <= count, set(arr))
greater_positive_num = 1
for num in arr:
if greater_positive_num == num:
@codecakes
codecakes / string_rotation.py
Last active September 5, 2022 18:04
Find if the rotated string2 is same as string1 which may include repeating characters.
# print(is_string_rotate("ABRACADA", "RACADAAB"))
# 1. increment string 1 char count
# 2. check string 2 count, inc & skip until match. if word count doesn't
# match in step 1, move to next character.
# 3. Return to step 1
# 4. Invariant: End when string1 count is exhausted.
def is_string_rotate(string1: str, string2: str) -> bool:
"""Returns True if string is rotated.
@codecakes
codecakes / reverse_sentence.py
Created September 4, 2022 21:38
Frame words in a phrase in reverse order the non-idiomatic unpythonic way
# Online Python - IDE, Editor, Compiler, Interpreter
import string
EXCLUDE_CHARS = {each_invalid_char: "" for each_invalid_char in string.punctuation}
SAME_CHARS = {**{w:w for w in string.ascii_letters}, **EXCLUDE_CHARS}
EXCLUDE_CHAR_MAP = str.maketrans(SAME_CHARS)
def reverse_string(sentence: str):