Perform String Shifts Python

You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
  • direction can be 0 (for left shift) or 1 (for right shift). 
  • amount is the amount by which string s is to be shifted.
  • A left shift by 1 means remove the first character of s and append it to the end.
  • Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.
Return the final string after all operations.

Example 1:
Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
Explanation: 
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"
class Solution:
    def stringShift(self, s: str, shift: List[List[int]]) -> str:
        l,ls,rs = len(s),0,0
        for direction , amount in shift:
            if direction == 0:
                ls+=amount
            else:
                rs+=amount
        ls = ls % l
        rs = rs % l
        if ls == rs:
            return s
        elif ls > rs:
            ls = ls -rs
            return s[ls:]+s[:ls]
        else:
            rs = rs -ls
            return s[-rs:]+s[:-rs]



            
        
        
        
        
            
            
            

Find the Difference Python

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.
Using sorting
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        x = sorted(s)
        y = sorted(t)
        i = 0
        while i < len(x):
            if x[i] != y[i]:
                return y[i]
            i+=1
        return y[i]
Time Complexity : O(nlogn)
Space Complexity : O(1) sorting in python takes inplace so O(1)
Using Hashmap :
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        counter_s = Counter(s)
        for ch in t:
            if ch not in counter_s or counter_s[ch] == 0:
                return ch
            else:
                counter_s[ch] -=1
Time Complexity : O(n)
Space Complexity : O(1)
Using Bit manipulation :
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        res = 0
        for i in s:
            res ^= ord(i)
            
        for i in t:
            res ^= ord(i)
            
        return chr(res)
Time Complexity : O(n)
Space complexity : O(1)

Contains Duplicate II Python

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Using Hashmap:
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        hashmap = {}
        for i in range(0,len(nums)):
            if nums[i] in hashmap and abs(hashmap[nums[i]] - i) <= k:
                return True
            else:
                hashmap[nums[i]] = i
        return False
Time Complexity : O(n)
Space Complexity :O(n,k) 

Number of Islands Python

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000

Output: 1
Example 2:
Input:
11000
11000
00100
00011

Output: 3
Using DFS Method:
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0
        rows = len(grid)
        cols = len(grid[0])
        def dfs(i,j,grid):
            if i < 0 or i >= rows or j >= cols or j < 0 or grid[i][j] == '0':
                return 
            grid[i][j] = "0"
            dfs(i+1,j,grid)
            dfs(i-1,j,grid)
            dfs(i,j+1,grid)
            dfs(i,j-1,grid)
            return 1
        noOfIslands = 0
        for i in range(0,rows):
            for j in range(0,cols):
                if grid[i][j] == "1":
                    noOfIslands+=dfs(i,j,grid)
        return noOfIslands
        
        
Time Complexity : O(M * N)
Space Complexity : O(M * N) Worst case 

Reverse Integer Python

Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

class Solution:
    def reverse(self, x: int) -> int:
        sign = -1 if x < 0 else 1
        x *= sign
        res = 0
        while x > 0:
            res = (res * 10) + x % 10
            x = x // 10
        res*=sign
        return res if abs(res) <= (2 ** 31) else 0
            
Space Complexity : O(1)
Time Complexity : O(n)

Plus One Python

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        for i in range(1,len(digits)+1):
            if digits[-i] < 9:
                digits[-i] +=1
                return digits
            digits[-i] = 0
        return [1] + digits
                
        
Time Complexity : O(n)
Space Complexity : O(1) when no 9 digits entirely O(N) if all elements are 9.

Fizz Buzz - Python

Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
Python Solution :
class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        liststr = []
        if n == 0:
            return 0
        for i in range(1,n+1):
            if i % 15 == 0:
                liststr.append("FizzBuzz")
            elif i % 3 == 0:
                liststr.append('Fizz')
            elif i % 5 == 0: 
                liststr.append('Buzz') 
            else:
                liststr.append(str(i))
        return liststr
        
Time Complexity : O(n)
Space Complexity : O(n)

Middle of the Linked List Python

Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.

Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:
  • The number of nodes in the given list will be between 1 and 100.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        pA = head
        if head is None:
            return head
        pA = head
        lA = 0
        while pA:
            lA+=1
            pA =pA.next
        pB = head
        lA = lA//2
        while lA != 0:
            pB = pB.next
            lA -= 1
        return pB if lA % 2 ==0 else pB.next
            
Time Complexity : O(n)
Space Complexity : O(1)


Fast Pointer and Slow Pointer :


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow
    
Time Complexity : O(n)
Space Complexity : O(1)           
            
        
        

Backspace String Compare Python

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and '#' characters.
Follow up:
  • Can you solve it in O(N) time and O(1) space?
Using stack :

Time Complexity : O(n) n is larger of both lengths of strings
Space Complexity : O(n)

class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        def build(S):
            stack = []
            for i in S:
                if i == '#' and stack:
                    stack.pop()
                elif i !='#':
                    stack.append(i)
            return ''.join(stack)
        return build(S) == build(T)


Using Two Pointers:


class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        def F(S):
            skip = 0
            for i in reversed(S):
                if i == '#':
                    skip+=1
                elif skip:
                    skip -=1
                else:
                    yield i
        return all(x == y for x,y in itertools.zip_longest(F(S),F(T)))
    
            
Time Complexity : O(n)
Space Complexity : O(1)
        

Find Peak Element Python

A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.
class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        l = 0
        r = len(nums)-1
        while(l < r):
            mid = l + (r-l) // 2
            if nums[mid] > nums[mid+1]:
                r = mid
            else:
                l = mid+1
        return l
                
        Time Complexity : O(logn)
        Space Complexity : O(1)

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...