0% found this document useful (0 votes)
57 views6 pages

Untitled6.ipynb - Colab

Uploaded by

yashsoan007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views6 pages

Untitled6.ipynb - Colab

Uploaded by

yashsoan007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

# Definition for a binary tree node.

# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right

class Solution:
def __init__(self):
self.prev = None # This will hold the previous node in post-order traversal

def flatten(self, root: Optional[TreeNode]) -> None:


"""
Do not return anything, modify root in-place instead.
"""
if not root:
return None

# Flatten left subtree first, then right subtree


self.flatten(root.left)
self.flatten(root.right)

# Set current node's right to previous node


root.right = self.prev
# Set current node's left to None
root.left = None
# Update prev to current node
self.prev = root

class Solution:
def minimumOperations(self, nums: List[int], target: List[int]) -> int:
a=[t-n for t,n in zip(target,nums)] #differences array
ans=0
def solve(a):
a=[0]+a # add 0 at left.
ans=0
for x,y in pairwise(a):
if x<y:
ans+=y-x
return ans
for g in groupby(a,lambda x: x<0):
ans+=solve(list([abs(x) for x in g[1]]))
return ans

class Solution:
def waysToReachStair(self, target: int) -> int:
current_sum = 1
ways = 0

if target == 0 or target == 1:
ways += 1

pas = [[0] * 50 for _ in range(50)]


pas[0][0] = 1

for row in range(1, 50):


pas[row][0] = 1
for col in range(1, row + 1):
pas[row][col] = pas[row - 1][col] + pas[row - 1][col - 1]

for i in range(30):
current_sum += 1 << i
if current_sum >= target and current_sum - target <= i + 2:
n = i + 2
r = current_sum - target
ways += pas[n][r]
return ways

# Python3 program for the above approach


import sys

# Function to find the maximum sum


# of sub-array
def maximumSubarraySum(arr) :

# Initialize the variables


N = len(arr);
memo = {};
res = -(sys.maxsize - 1);
currsum = 0;
currval = 0;

# Traverse over the range


for i in range(N) :

# Add the current value to the


# variable currsum for prefix sum
currval = arr[i];
currsum = currsum + currval;

# Calculate the result


if currval in memo :

if (currval > 0) :
res = max(res,currsum - memo[currval] + currval);
else :
res = max(res,currsum - memo[currval] + 2 * currval);

else :
memo[currval] = currsum;

if (currval < 0) :
currsum = currsum - currval;

# Return the answer


return res;

class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1])
ans, t = 0, intervals[0][1]

for s, e in intervals[1:]:
if s >= t:
t = e
else:
ans += 1

return ans

def maximize_value(n, k, arr):


# Sort the array
arr.sort()
res = 0

for i in range(k):
res += max(0, arr[n - 1 - i] - i)

return res
def maximize_value(n, k, arr):
# Sort the array
arr.sort()
res = 0

for i in range(k):
res += max(0, arr[n - k - i] - i)

return res

from typing import List

class Solution:
def find_prime_pairs(self, n: int) -> List[List[int]]:
# Edge case: if n is less than 4, no prime pairs can sum to it
if n < 4:
return []

# Initialize a list to mark all numbers as prime initially


is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False # 0 and 1 are not prime numbers

# Sieve of Eratosthenes algorithm to find all primes up to n


for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
# Mark multiples of i as non-prime
for j in range(i * i, n + 1, i):
is_prime[j] = False

# Initialize a list to store pairs of prime numbers


prime_pairs = []

# Find pairs of primes where both numbers add up to n


for x in range(2, n // 2 + 1):
y = n - x
# If both x and y are prime, add them as a pair
if is_prime[x] and is_prime[y]:
prime_pairs.append([x, y])

# Return the list of prime pairs


return prime_pairs

class Solution:
def queryString(self, s: str, n: int) -> bool:
for i in range(1,n+1):
if bin(i)[2:] not in s:return False
return True

from typing import List

def min_number_of_strikers(targets: List[List[int]]) -> int:


# Sort targets by the end coordinate
targets.sort(key=lambda x: x[1])

strikers = 0
last_striker_position = float('-inf') # Initialize to negative infinity
for x_start, x_end in targets:
# If the current striker cannot cover this target, place a new striker
if x_start > last_striker_position:
strikers += 1
last_striker_position = x_end # Place the striker at the end of the current target

return strikers

from typing import List

def inventory_management(products: List[int], changes: List[int]) -> List[int]:


# Dictionary to keep track of the current stock levels for each product
stock_levels = {product: 0 for product in products}
inventory_status = []

# Process each change and update stock levels


for i in range(len(changes)):
product_id = products[i]
change = changes[i]

# Update stock level for the current product


stock_levels[product_id] += change

# Find the maximum stock level after the update


max_stock = max(stock_levels.values())

# Append the maximum stock level to the result (0 if all stocks are non-positive)
inventory_status.append(max_stock if max_stock > 0 else 0)

return inventory_status

# Find the longest consecutive sequence of zig-zag numbers in a list of numbers.


# A number is a zig-zag number if it is greater than both its neighbors or less than both its neighbors.

def longest_zigzag_sequence(numbers):
# Initialize the longest sequence length to 1
longest_sequence_length = 1
# List with size equal to the input list, initialized with 1
sequence_lengths_larger = [1] * len(numbers)
sequence_lengths_smaller = [1] * len(numbers)
# Iterate through the numbers
for i in range(1, len(numbers)):
if(numbers[i] > numbers[i - 1]):
sequence_lengths_larger[i] = sequence_lengths_smaller[i - 1] + 1
sequence_lengths_smaller[i] = 1
elif(numbers[i] < numbers[i - 1]):
sequence_lengths_smaller[i] = sequence_lengths_larger[i - 1] + 1
sequence_lengths_larger[i] = 1
else:
sequence_lengths_larger[i] = 1
sequence_lengths_smaller[i] = 1
#Find the longest sequence
for i in range(len(numbers)):
longest_sequence_length = max(longest_sequence_length, max(sequence_lengths_larger[i], sequence_lengths_smaller[i]))
return longest_sequence_length

# Test the function with some sample inputs


print(longest_zigzag_sequence([10,5,3,11,8,9,9,2,10]))

Numerix waale ka voh ni chala toh

def count_subarrays(nums, k, p):


# Initialize a set to store unique sub-arrays
unique_subarrays = set()
# Iterate over the array to consider every starting point
for i in range(len(nums)):
divisible_count = 0 # Counter for numbers divisible by p
subarray = [] # Current sub-array being checked

# Slide the window starting from 'i'


for j in range(i, len(nums)):
subarray.append(nums[j]) # Add current element to sub-array

# If the current element is divisible by p, increase the counter


if nums[j] % p == 0:
divisible_count += 1

# If more than 'k' numbers divisible by 'p' are found, stop this sub-array
if divisible_count > k:
break

# Convert subarray to a tuple (since lists are not hashable) and add to set
unique_subarrays.add(tuple(subarray))

# Return the number of unique sub-arrays found


return len(unique_subarrays)

# Example usage:
nums = [1,2,3,4] # The array from the example
k = 4 # Maximum numbers divisible by p allowed in a sub-array
p = 1 # The magical number

# Call the function and print the result


result = count_subarrays(nums, k, p)
print(result) # Expected output is 11 based on the given example

def non_mirror_string(word):
from collections import Counter

n = len(word)
if n % 2 != 0:
return "-1" # Ensure the word has even length.

# Count occurrences of each character


char_count = Counter(word)

# Check if any character occurs more than n/2 times


if any(count > n // 2 for count in char_count.values()):
return "-1"

# Create a sorted list of characters


sorted_chars = sorted(word)

# Result list to hold the rearranged characters


result = [''] * n

# Fill the result in a way that avoids mirror conditions


mid = n // 2
result[:mid] = sorted_chars[:mid]
result[mid:] = sorted_chars[mid:]

# Ensure no mirror condition occurs


for i in range(mid):
if result[i] == result[n - 1 - i]:
return "-1"

return ''.join(result)

# Example Usage
print(non_mirror_string("zadz")) # Expected Output: "adzz"
print(non_mirror_string("zyyz")) # Expected Output: "yyzz"
print(non_mirror_string("qqqt")) # Expected Output: "-1"

You might also like