diff --git a/3sum.py b/3sum.py new file mode 100644 index 0000000..c2ac965 --- /dev/null +++ b/3sum.py @@ -0,0 +1,34 @@ +def threeSum(nums): + nums.sort() + result = [] + n = len(nums) + + for i in range(n - 2): + # Skip duplicate values for i + if i > 0 and nums[i] == nums[i - 1]: + continue + + left = i + 1 + right = n - 1 + + while left < right: + total = nums[i] + nums[left] + nums[right] + + if total == 0: + result.append([nums[i], nums[left], nums[right]]) + + # Skip duplicates for left and right + while left < right and nums[left] == nums[left + 1]: + left += 1 + while left < right and nums[right] == nums[right - 1]: + right -= 1 + + left += 1 + right -= 1 + + elif total < 0: + left += 1 + else: + right -= 1 + + return result diff --git a/4sum.py b/4sum.py new file mode 100644 index 0000000..1be776c --- /dev/null +++ b/4sum.py @@ -0,0 +1,39 @@ +def fourSum(nums, target): + nums.sort() + n = len(nums) + result = [] + + for i in range(n - 3): + # Skip duplicates for first number + if i > 0 and nums[i] == nums[i - 1]: + continue + + for j in range(i + 1, n - 2): + # Skip duplicates for second number + if j > i + 1 and nums[j] == nums[j - 1]: + continue + + left = j + 1 + right = n - 1 + + while left < right: + total = nums[i] + nums[j] + nums[left] + nums[right] + + if total == target: + result.append([nums[i], nums[j], nums[left], nums[right]]) + + # Skip duplicates for left and right + while left < right and nums[left] == nums[left + 1]: + left += 1 + while left < right and nums[right] == nums[right - 1]: + right -= 1 + + left += 1 + right -= 1 + + elif total < target: + left += 1 + else: + right -= 1 + + return result diff --git a/Basic python code.py b/Basic python code.py new file mode 100644 index 0000000..a25e7d7 --- /dev/null +++ b/Basic python code.py @@ -0,0 +1,125 @@ +#1. Print “Hello World” +print("Hello World") + + +#2. Sum of two numbers +a = 10 +b = 20 +sum = a + b +print("Sum =", sum) + + + + +#3 Check whether a number is even or odd +num = 7 + +if num % 2 == 0: + print("Even") +else: + print("Odd") + + + + +#4 . Find the largest of two numbers +a = 10 +b = 20 + +if a > b: + print("Largest =", a) +else: + print("Largest =", b) + + + +#5 Print numbers from 1 to 10 +for i in range(1, 11): + print(i) + + + +#6 Find factorial of a number +num = 5 +fact = 1 + +for i in range(1, num + 1): + fact = fact * i + +print("Factorial =", fact) + + + +#7 check whether a number is prime +num = 7 +flag = True + +if num <= 1: + flag = False + +for i in range(2, num): + if num % i == 0: + flag = False + break + +if flag: + print("Prime number") +else: + print("Not a prime number") + + + + +#8 Reverse a string +s = "python" +rev = "" + +for ch in s: + rev = ch + rev + +print("Reversed string =", rev) + + + +#9 s = "python" +rev = "" + +for ch in s: + rev = ch + rev + +print("Reversed string =", rev) + + + +#10. Find sum of elements in a list +list1 = [1, 2, 3, 4, 5] +total = 0 + +for i in list1: + total += i + +print("Sum =", total) + + + +#11. Function to add two numbers +def add(a, b): + return a + b + +print(add(5, 3)) + + + + +#12 Check even/odd using function +def check_even_odd(num): + if num % 2 == 0: + return "Even" + else: + return "Odd" + + + + + + diff --git "a/Boyer\342\200\223Moore Voting Algorithm.py" "b/Boyer\342\200\223Moore Voting Algorithm.py" new file mode 100644 index 0000000..635b766 --- /dev/null +++ "b/Boyer\342\200\223Moore Voting Algorithm.py" @@ -0,0 +1,26 @@ +def majorityElement(nums): + # Step 1: Find potential candidates + count1 = count2 = 0 + candidate1 = candidate2 = None + + for num in nums: + if num == candidate1: + count1 += 1 + elif num == candidate2: + count2 += 1 + elif count1 == 0: + candidate1, count1 = num, 1 + elif count2 == 0: + candidate2, count2 = num, 1 + else: + count1 -= 1 + count2 -= 1 + + # Step 2: Verify the candidates + result = [] + if nums.count(candidate1) > len(nums) // 3: + result.append(candidate1) + if candidate2 != candidate1 and nums.count(candidate2) > len(nums) // 3: + result.append(candidate2) + + return result diff --git a/First Unique Character in a String.py b/First Unique Character in a String.py new file mode 100644 index 0000000..cbdab7c --- /dev/null +++ b/First Unique Character in a String.py @@ -0,0 +1,11 @@ +def firstUniqChar(s): + freq = {} + + for ch in s: + freq[ch] = freq.get(ch, 0) + 1 + + for i, ch in enumerate(s): + if freq[ch] == 1: + return i + + return -1 diff --git "a/Range Sum Query \342\200\223 Immutable.py" "b/Range Sum Query \342\200\223 Immutable.py" new file mode 100644 index 0000000..3c78dee --- /dev/null +++ "b/Range Sum Query \342\200\223 Immutable.py" @@ -0,0 +1,9 @@ +class NumArray: + + def __init__(self, nums): + self.prefix = [0] + for num in nums: + self.prefix.append(self.prefix[-1] + num) + + def sumRange(self, left, right): + return self.prefix[right + 1] - self.prefix[left] diff --git a/Range Sum Query.py b/Range Sum Query.py new file mode 100644 index 0000000..e640290 --- /dev/null +++ b/Range Sum Query.py @@ -0,0 +1,31 @@ +class NumArray: + + def __init__(self, nums): + self.prefix = [0] + for num in nums: + self.prefix.append(self.prefix[-1] + num) + + def sumRange(self, left: int, right: int) -> int: + return self.prefix[right + 1] - self.prefix[left] + + + + + + +#Binary Search +class Solution: + def search(self, nums, target): + left, right = 0, len(nums) - 1 + + while left <= right: + mid = (left + right) // 2 + + if nums[mid] == target: + return mid + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + return -1 diff --git a/add binary.py b/add binary.py new file mode 100644 index 0000000..748b586 --- /dev/null +++ b/add binary.py @@ -0,0 +1,20 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + i, j = len(a) - 1, len(b) - 1 + carry = 0 + result = [] + + while i >= 0 or j >= 0 or carry: + total = carry + + if i >= 0: + total += int(a[i]) + i -= 1 + if j >= 0: + total += int(b[j]) + j -= 1 + + result.append(str(total % 2)) + carry = total // 2 + + return ''.join(reversed(result)) diff --git a/assignment 1.py b/assignment 1.py new file mode 100644 index 0000000..ecd863c --- /dev/null +++ b/assignment 1.py @@ -0,0 +1,205 @@ +#1 Simple function which prints “Name” +def print_name(): + print("Piyush") + +print_name() + + + + +#2 Function which expects two arguments and prints them +def print_two(a, b): + print(a) + print(b) + +print_two(10, 20) + + + + +#3 Function which expects an unknown number of arguments +def print_args(*args): + for i in args: + print(i) + +print_args(1, 2, 3, 4, 5) + + + + + +#4 Function which expects keyword arguments (kwargs) +def print_kwargs(**kwargs): + for key, value in kwargs.items(): + print(key, ":", value) + +print_kwargs(name="Piyush", age=21, course="Python") + + + + + +#5 Function which expects a list as an argument +def print_list(lst): + for item in lst: + print(item) + +print_list([10, 20, 30, 40]) + + + + + +#6 Function to find the maximum of four numbers +def max_of_four(a, b, c, d): + return max(a, b, c, d) + +print(max_of_four(10, 25, 5, 15)) + + + + + +#7 Function to sum all numbers in a list +def sum_list(lst): + total = 0 + for i in lst: + total += i + return total + +print(sum_list([1, 2, 3, 4, 5])) + + + + + + +#8 Function to multiply all numbers in a list +def multiply_list(lst): + result = 1 + for i in lst: + result *= i + return result + +print(multiply_list([1, 2, 3, 4])) + + + + + + +#9 Function to check whether a number falls in a given range +def check_range(num, start, end): + if start <= num <= end: + return True + else: + return False + +print(check_range(10, 5, 15)) + + + + + + +#10 Function to check whether a number is even or odd +def even_or_odd(num): + if num % 2 == 0: + print("Even") + else: + print("Odd") + +even_or_odd(7) + + + +#11 +def unique_list(lst): + unique = [] + for item in lst: + if item not in unique: + unique.append(item) + return unique + +# Example +print(unique_list([1, 2, 2, 3, 4, 4, 5])) + + + + + +#12 +def is_prime(n): + if n <= 1: + return False + for i in range(2, n): + if n % i == 0: + return False + return True + +# Example +num = 7 +if is_prime(num): + print("Prime number") +else: + print("Not a prime number") + + + + +#13 +def print_even_numbers(lst): + for num in lst: + if num % 2 == 0: + print(num, end=" ") + +# Sample List +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] +print_even_numbers(numbers) + + + + + +#14 +def is_palindrome(s): + return s == s[::-1] + +# Example +word = "madam" +if is_palindrome(word): + print("Palindrome") +else: + print("Not a palindrome") + + + + + +#15 +def find_min(a, b, c): + return min(a, b, c) + +# Example +print(find_min(10, 5, 8)) + + + +#21 +def isAnagram(s: str, t: str) -> bool: + if len(s) != len(t): + return False + + count = [0] * 26 + + for ch in s: + count[ord(ch) - ord('a')] += 1 + + for ch in t: + count[ord(ch) - ord('a')] -= 1 + + for c in count: + if c != 0: + return False + + return True diff --git a/assignment 4.py b/assignment 4.py new file mode 100644 index 0000000..4914d58 --- /dev/null +++ b/assignment 4.py @@ -0,0 +1,132 @@ +# ============================================ +# EXCEPTION HANDLING – ALL IN ONE PYTHON FILE +# ============================================ + +# 1. Python script to CREATE an ArithmeticError +print("\n1. Creating ArithmeticError") +try: + x = 10 / 0 # Division by zero +except Exception as e: + print("ArithmeticError created:", e) + + +# 2. Python script to CREATE a ValueError +print("\n2. Creating ValueError") +try: + num = int("abc") # Invalid conversion +except Exception as e: + print("ValueError created:", e) + + +# 3. Python script to HANDLE ArithmeticError +print("\n3. Handling ArithmeticError") +try: + a = 20 / 0 +except ArithmeticError: + print("ArithmeticError handled successfully") + + +# 4. Python script to HANDLE ValueError +print("\n4. Handling ValueError") +try: + value = int("xyz") +except ValueError: + print("ValueError handled successfully") + + +# 5. Python script to HANDLE MULTIPLE exceptions in ONE try +print("\n5. Handling Multiple Exceptions") +try: + num1 = int(input("Enter first number: ")) + num2 = int(input("Enter second number: ")) + print(num1 / num2) +except ValueError: + print("Invalid input! Please enter numbers only.") +except ZeroDivisionError: + print("Cannot divide by zero.") + + +# 6. Calculator with 4 basic operations and MAX exception handling +print("\n6. Calculator with Exception Handling") + +try: + a = float(input("Enter first number: ")) + b = float(input("Enter second number: ")) + op = input("Enter operation (+, -, *, /): ") + + if op == "+": + print("Result:", a + b) + elif op == "-": + print("Result:", a - b) + elif op == "*": + print("Result:", a * b) + elif op == "/": + print("Result:", a / b) + else: + raise ValueError("Invalid operation selected") + +except ValueError as ve: + print("ValueError:", ve) +except ZeroDivisionError: + print("Error: Division by zero") +except Exception as e: + print("Unexpected Error:", e) + + +# 7. Adding FINALLY block to the calculator +print("\n7. Calculator with FINALLY block") + +try: + x = int(input("Enter a number: ")) + y = int(input("Enter another number: ")) + print("Division:", x / y) +except ZeroDivisionError: + print("Cannot divide by zero") +except ValueError: + print("Invalid input") +finally: + print("Execution completed (finally block executed)") + + +# 8. Try-Except-Else block for DIVISION +print("\n8. Try-Except-Else Example") + +try: + m = int(input("Enter numerator: ")) + n = int(input("Enter denominator: ")) + result = m / n +except ZeroDivisionError: + print("Denominator cannot be zero") +except ValueError: + print("Enter valid integers") +else: + print("Division Result:", result) + + +# 9. Python script to RAISE a ValueError +print("\n9. Raising a ValueError manually") + +age = int(input("Enter your age: ")) +if age < 0: + raise ValueError("Age cannot be negative") +else: + print("Valid age:", age) + + +# 10. Nested Try-Except Block +print("\n10. Nested Try-Except Example") + +try: + num = int(input("Enter a number: ")) + try: + result = 10 / num + print("Result:", result) + except ZeroDivisionError: + print("Inner Try: Division by zero") +except ValueError: + print("Outer Try: Invalid number input") + + +# ============================================ +# END OF FILE +# ============================================ diff --git a/assignment question 15-20.py b/assignment question 15-20.py new file mode 100644 index 0000000..d6e61f2 --- /dev/null +++ b/assignment question 15-20.py @@ -0,0 +1,84 @@ +#15. Program to find the minimum of three numbers using a function +def find_min(a, b, c): + return min(a, b, c) + +print("Minimum =", find_min(10, 5, 8)) + + + + + + +#16. Program to print a list of squares of numbers between 1 and 30 +def square_list(): + result = [] + for i in range(1, 31): + result.append(i * i) + return result + +print(square_list()) + + + + +#17. Program to access a function inside another function +def inner(): + print("This is inner function") + +def outer(): + print("This is outer function") + inner() + +outer() + + + + +#18 Program to count uppercase and lowercase letters in a string +def count_letters(s): + upper = 0 + lower = 0 + + for ch in s: + if ch.isupper(): + upper += 1 + elif ch.islower(): + lower += 1 + + print("Uppercase letters:", upper) + print("Lowercase letters:", lower) + +count_letters("Hello World") + + + + + +#19 Program to check whether a string is a pangram +def is_pangram(s): + s = s.lower() + for ch in "abcdefghijklmnopqrstuvwxyz": + if ch not in s: + return False + return True + +string = "The quick brown fox jumps over the lazy dog" +print(is_pangram(string)) + + + + + +#20 Program to check whether two strings are anagrams +def is_anagram(s1, s2): + s1 = s1.replace(" ", "").lower() + s2 = s2.replace(" ", "").lower() + + return sorted(s1) == sorted(s2) + +print(is_anagram("listen", "silent")) + + + + + diff --git a/binary search.py b/binary search.py new file mode 100644 index 0000000..e70dd9b --- /dev/null +++ b/binary search.py @@ -0,0 +1,15 @@ +def binary_search(arr, target): + left = 0 + right = len(arr) - 1 + + while left <= right: + mid = (left + right) // 2 + + if arr[mid] == target: + return mid # element found + elif arr[mid] < target: + left = mid + 1 # search right half + else: + right = mid - 1 # search left half + + return -1 # element not found diff --git a/container most water.py b/container most water.py new file mode 100644 index 0000000..09304cd --- /dev/null +++ b/container most water.py @@ -0,0 +1,17 @@ +def maxArea(height): + left = 0 + right = len(height) - 1 + max_water = 0 + + while left < right: + width = right - left + curr_height = min(height[left], height[right]) + max_water = max(max_water, width * curr_height) + + # Move the pointer with smaller height + if height[left] < height[right]: + left += 1 + else: + right -= 1 + + return max_water diff --git a/contains dupicate.py b/contains dupicate.py new file mode 100644 index 0000000..74fefc4 --- /dev/null +++ b/contains dupicate.py @@ -0,0 +1,3 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) \ No newline at end of file diff --git a/delete dupliactes from sorted list.py b/delete dupliactes from sorted list.py new file mode 100644 index 0000000..40e1a68 --- /dev/null +++ b/delete dupliactes from sorted list.py @@ -0,0 +1,18 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def deleteDuplicates(self, head): + current = head + + while current and current.next: + if current.val == current.next.val: + # remove duplicate + current.next = current.next.next + else: + current = current.next + + return head diff --git a/implement stack using queue.py b/implement stack using queue.py new file mode 100644 index 0000000..d9c5c80 --- /dev/null +++ b/implement stack using queue.py @@ -0,0 +1,22 @@ +from collections import deque + +class MyStack: + + def __init__(self): + self.q = deque() + + def push(self, x: int) -> None: + self.q.append(x) + + # Rotate queue + for _ in range(len(self.q) - 1): + self.q.append(self.q.popleft()) + + def pop(self) -> int: + return self.q.popleft() + + def top(self) -> int: + return self.q[0] + + def empty(self) -> bool: + return not self.q \ No newline at end of file diff --git a/majority element.py b/majority element.py new file mode 100644 index 0000000..42f7894 --- /dev/null +++ b/majority element.py @@ -0,0 +1,14 @@ +def majorityElement(nums): + count = 0 + candidate = None + + for num in nums: + if count == 0: + candidate = num + + if num == candidate: + count += 1 + else: + count -= 1 + + return candidate diff --git a/majority.py b/majority.py new file mode 100644 index 0000000..d0a184c --- /dev/null +++ b/majority.py @@ -0,0 +1,12 @@ +n = [2,2,1,1,1,2,2] +d = {} + +for v in n: + if v in d: + d[v] += 1 + else: + d[v] = 1 + +for key in d: + if d[key] > len(n) // 2: + print(key) diff --git a/maximum sub array.py b/maximum sub array.py new file mode 100644 index 0000000..2ba7680 --- /dev/null +++ b/maximum sub array.py @@ -0,0 +1,12 @@ +nums = [5, 4, -1, 7, 8] + +current_sum = 0 +max_value = nums[0] + +for v in nums: + current_sum += v + max_value = max(max_value, current_sum) + if current_sum < 0: + current_sum = 0 + +print(max_value) diff --git a/merge two sorted list.py b/merge two sorted list.py new file mode 100644 index 0000000..1336cff --- /dev/null +++ b/merge two sorted list.py @@ -0,0 +1,24 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +def mergeTwoLists(list1, list2): + dummy = ListNode() # starting point + current = dummy + + # Traverse both lists + while list1 and list2: + if list1.val <= list2.val: + current.next = list1 + list1 = list1.next + else: + current.next = list2 + list2 = list2.next + current = current.next + + # Attach remaining nodes + current.next = list1 if list1 else list2 + + return dummy.next diff --git a/moves zeros.py b/moves zeros.py new file mode 100644 index 0000000..a0a1594 --- /dev/null +++ b/moves zeros.py @@ -0,0 +1,12 @@ +def moveZeroes(nums): + k = 0 # position for next non-zero element + + # Move all non-zero elements forward + for i in range(len(nums)): + if nums[i] != 0: + nums[k] = nums[i] + k += 1 + + # Fill remaining positions with zeros + for i in range(k, len(nums)): + nums[i] = 0 diff --git a/new.py b/new.py new file mode 100644 index 0000000..ff4e46a --- /dev/null +++ b/new.py @@ -0,0 +1,16 @@ +a,b= 10,20 + +print("sum of {} and {} is : {}".format(a,b,a+b)) + + +name = "JAADU" +s = list(name) +print("".join(s)) + + +print(name[:: -1]) + +print(name[5:: -1]) + + + diff --git a/next greater element.py b/next greater element.py new file mode 100644 index 0000000..22e90ef --- /dev/null +++ b/next greater element.py @@ -0,0 +1,18 @@ +def next_greater(arr): + stack = [] + result = [-1] * len(arr) + + for i in range(len(arr) - 1, -1, -1): + + while stack and stack[-1] <= arr[i]: + stack.pop() + + result[i] = stack[-1] if stack else -1 + + stack.append(arr[i]) + + return result + + +arr = [4, 5, 2, 10, 8] +print(next_greater(arr)) \ No newline at end of file diff --git a/no of recent calls.py b/no of recent calls.py new file mode 100644 index 0000000..b2e63c7 --- /dev/null +++ b/no of recent calls.py @@ -0,0 +1,17 @@ +from collections import deque + +class RecentCounter: + + def __init__(self): + self.q = deque() + + def ping(self, t: int) -> int: + # Add new request + self.q.append(t) + + # Remove requests older than t - 3000 + while self.q[0] < t - 3000: + self.q.popleft() + + # Return number of valid requests + return len(self.q) \ No newline at end of file diff --git a/optimized b/optimized new file mode 100644 index 0000000..7b82b81 --- /dev/null +++ b/optimized @@ -0,0 +1,15 @@ +def twoSum(nums, target): + ind = 0 + m = {} + + for val in nums: + res = target - val + if res in m: + return [m[res], ind] + m[val] = ind + ind += 1 + + +n = [2, 7, 11, 15] +print(twoSum(n, 9)) + diff --git a/palindrome linked list.py b/palindrome linked list.py new file mode 100644 index 0000000..6e402a4 --- /dev/null +++ b/palindrome linked list.py @@ -0,0 +1,36 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + if not head or not head.next: + return True + + # Step 1: Find middle using slow & fast pointers + slow = fast = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # Step 2: Reverse second half + prev = None + while slow: + temp = slow.next + slow.next = prev + prev = slow + slow = temp + + # Step 3: Compare both halves + left = head + right = prev + + while right: + if left.val != right.val: + return False + left = left.next + right = right.next + + return True \ No newline at end of file diff --git a/palindrome linked list2.py b/palindrome linked list2.py new file mode 100644 index 0000000..113f330 --- /dev/null +++ b/palindrome linked list2.py @@ -0,0 +1,35 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + if not head or not head.next: + return True + + # Step 1: Find middle of the linked list + slow = fast = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # Step 2: Reverse second half + prev = None + while slow: + temp = slow.next + slow.next = prev + prev = slow + slow = temp + + # Step 3: Compare both halves + left = head + right = prev + while right: + if left.val != right.val: + return False + left = left.next + right = right.next + + return True \ No newline at end of file diff --git a/prefix sufix.py b/prefix sufix.py new file mode 100644 index 0000000..d72db09 --- /dev/null +++ b/prefix sufix.py @@ -0,0 +1,25 @@ +def productExceptSelf(nums): + n = len(nums) + answer = [1] * n + + # Prefix product + prefix = 1 + for i in range(n): + answer[i] = prefix + prefix *= nums[i] + + # Suffix product + suffix = 1 + for i in range(n - 1, -1, -1): + answer[i] *= suffix + suffix *= nums[i] + + return answer + + +# Example +nums = [1, 2, 3, 4] +print(productExceptSelf(nums)) # Output: [24, 12, 8, 6] + + + \ No newline at end of file diff --git a/product of array except self.py b/product of array except self.py new file mode 100644 index 0000000..4b40642 --- /dev/null +++ b/product of array except self.py @@ -0,0 +1,24 @@ +def productExceptSelf(nums): + n = len(nums) + answer = [1] * n + + # Step 1: Prefix products + prefix = 1 + for i in range(n): + answer[i] = prefix + prefix *= nums[i] + + # Step 2: Suffix products + suffix = 1 + for i in range(n - 1, -1, -1): + answer[i] *= suffix + suffix *= nums[i] + + return answer + + +# ----------- Driver Code (VS Code) ----------- +if __name__ == "__main__": + nums = list(map(int, input("Enter array elements: ").split())) + result = productExceptSelf(nums) + print("Output:", result) diff --git a/remove nth node from end of list.py b/remove nth node from end of list.py new file mode 100644 index 0000000..5eb8e79 --- /dev/null +++ b/remove nth node from end of list.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + dummy = ListNode(0) + dummy.next = head + + fast = dummy + slow = dummy + + # Move fast pointer n+1 steps ahead + for _ in range(n + 1): + fast = fast.next + + # Move both pointers until fast reaches the end + while fast: + fast = fast.next + slow = slow.next + + # Remove the nth node from end + slow.next = slow.next.next + + return dummy.next diff --git a/reverse linked list.py b/reverse linked list.py new file mode 100644 index 0000000..6716035 --- /dev/null +++ b/reverse linked list.py @@ -0,0 +1,18 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + prev = None + curr = head + + while curr: + next_node = curr.next # store next node + curr.next = prev # reverse pointer + prev = curr # move prev forward + curr = next_node # move curr forward + + return prev diff --git a/reverse linked list2.py b/reverse linked list2.py new file mode 100644 index 0000000..0855131 --- /dev/null +++ b/reverse linked list2.py @@ -0,0 +1,29 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: + if not head or left == right: + return head + + # Dummy node to handle edge cases + dummy = ListNode(0) + dummy.next = head + prev = dummy + + # Move prev to the node before 'left' + for _ in range(left - 1): + prev = prev.next + + # Start reversing + curr = prev.next + for _ in range(right - left): + temp = curr.next + curr.next = temp.next + temp.next = prev.next + prev.next = temp + + return dummy.next diff --git a/rotate list.py b/rotate list.py new file mode 100644 index 0000000..f586cb2 --- /dev/null +++ b/rotate list.py @@ -0,0 +1,37 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def rotateRight(self, head: ListNode, k: int) -> ListNode: + # Edge cases + if not head or not head.next or k == 0: + return head + + # Step 1: find length and last node + length = 1 + last = head + while last.next: + last = last.next + length += 1 + + # Step 2: make list circular + last.next = head + + # Step 3: effective rotations + k = k % length + steps_to_new_tail = length - k - 1 + + # Step 4: find new tail + new_tail = head + for _ in range(steps_to_new_tail): + new_tail = new_tail.next + + # Step 5: break the circle + new_head = new_tail.next + new_tail.next = None + + return new_head diff --git a/two sum.py b/two sum.py new file mode 100644 index 0000000..c7445c3 --- /dev/null +++ b/two sum.py @@ -0,0 +1,18 @@ +def twoSum(num, target): + x = 0 + length = len(num) + + while x < length: + z = x + 1 + while z < length: + if num[x] + num[z] == target: + return [x, z] + z += 1 + x += 1 + + +n = [2, 7, 11, 15] +print(twoSum(n, 9)) + + + \ No newline at end of file diff --git a/uni charactor in string.py b/uni charactor in string.py new file mode 100644 index 0000000..7b93f08 --- /dev/null +++ b/uni charactor in string.py @@ -0,0 +1,12 @@ +class Solution: + def firstUniqChar(self, s: str) -> int: + freq = {} + + for ch in s: + freq[ch] = freq.get(ch, 0) + 1 + + for i in range(len(s)): + if freq[s[i]] == 1: + return i + + return -1 diff --git a/valid parenthesis.py b/valid parenthesis.py new file mode 100644 index 0000000..e520a81 --- /dev/null +++ b/valid parenthesis.py @@ -0,0 +1,17 @@ +def isValid(s: str) -> bool: + stack = [] + mapping = { + ')': '(', + '}': '{', + ']': '[' + } + + for char in s: + if char in mapping: # closing bracket + if not stack or stack[-1] != mapping[char]: + return False + stack.pop() + else: # opening bracket + stack.append(char) + + return len(stack) == 0 \ No newline at end of file