Compare Strings by Frequency of the Smallest Character Python

Let's define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2.
Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words.

Example 1:
Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
Example 2:
Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
class Solution:
    def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
        answers = []
        wordcount = sorted([word.count(min(word)) for word in words])
        for query in queries:
            querycount = query.count(min(query))
            pos = bisect.bisect(wordcount, querycount)
            answers.append(len(wordcount) - pos)
        return answers

Logger Rate Limiter Python

Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.
Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.
It is possible that several messages arrive roughly at the same time.
Example:
Logger logger = new Logger();

// logging string "foo" at timestamp 1
logger.shouldPrintMessage(1, "foo"); returns true; 

// logging string "bar" at timestamp 2
logger.shouldPrintMessage(2,"bar"); returns true;

// logging string "foo" at timestamp 3
logger.shouldPrintMessage(3,"foo"); returns false;

// logging string "bar" at timestamp 8
logger.shouldPrintMessage(8,"bar"); returns false;

// logging string "foo" at timestamp 10
logger.shouldPrintMessage(10,"foo"); returns false;

// logging string "foo" at timestamp 11
logger.shouldPrintMessage(11,"foo"); returns true;
class Logger:

    def __init__(self):

        self.inputMap = {}

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
         if message not in self.inputMap:
            self.inputMap[message] = timestamp
            return True        
         elif message in self.inputMap and timestamp - self.inputMap[message] >= 10:
            self.inputMap[message] = timestamp
            return True        
         else:
            return False



Time Complexity : O(1)
Space Complexity : O(n)

Two Sum Python

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].
// Single Pass method using HashTable
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        inputMap = {}
        for i in range(0, len(nums)):
            if target - nums[i] in inputMap and i != inputMap[target - nums[i]]:
                return [inputMap[target - nums[i]], i]
            else:
                inputMap[nums[i]] = i





Time Complexity : O(n)
Space Complexity : O(n)

Move Zeroes Python

Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
// Two Pointer Technique 
// Slow pointer and fast pointer technique


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """        Do not return anything, modify nums in-place instead.        """        i, j = 0, 0        for i in range(0, len(nums)):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1

Time Complexity : O(n)
Space Complexity : O(1)

Maximum Subarray Python

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_sum = nums[0]
        
        for i in range(1,len(nums)):
            if nums[i-1] > 0:
                nums[i] += nums[i-1]
            max_sum = max(max_sum,nums[i])
        return max_sum
       



Maximum Subarray Python

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Greedy Approach:
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if nums is None:
            return None        maxValue = nums[0]
        maxSubArrayValue = nums[0]
        for i in range(1, len(nums)):
            maxValue = max(nums[i], maxValue + nums[i])
            maxSubArrayValue = max(maxValue, maxSubArrayValue)
        return maxSubArrayValue

Time Complexity : O(n)
Space Complexity : O(1)

Valid Parentheses Python

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
An input string is valid if:
  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mapping = {"}": "{", "]": "[", ")": "("}
        for char in s:
            if char in mapping:
                top_element = stack.pop() if stack else "$"
                if top_element != mapping[char]:
                    return False
            else:
                stack.append(char)
        return not stack

Time Complexity : O(n)
Space Complexity : O(n)




Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...