Skip to main content

Posts

Showing posts with the label python3

LeetCode 26 — Remove Duplicates from Sorted Array

LeetCode 26 — Remove Duplicates from Sorted Array 1)approach 1 (Using extra list — not optimal) Works correctly but uses extra space and has O(n²) behavior because if i not in uniques is an O(n) check for each element. class Solution: def removeDuplicates(self, nums: List[int]) -> int: uniques = [] for i in nums: if i not in uniques: uniques.append(i) k = len(uniques) for i in range(k): nums[i] = uniques[i] return k Complexity: Time O(n²), Space O(n). Not in-place as required by the problem. 2) Optimal two-pointer solution (Front write — O(n), O(1) space) This is the recommended in-place approach for a sorted array: keep a write pointer p that marks the last unique position. class Solution: def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 p = 0 for i in range(1, len(nums)): ...

Solution: LeetCode 27 — Remove Element

LeetCode 27 — Remove Element Solution 1 (Optimal) This version is in-place, single-pass, O(n) time and O(1) space. It preserves the relative order of kept elements. class Solution: def removeElement(self, nums: List[int], val: int) -> int: p = 0 for i in nums: if i != val: nums[p] = i p += 1 return p Solution 2(Optimal) This version is in-place, single-pass, O(n) time and O(1) space. It preserves the relative order of kept elements. class Solution: def removeElement(self, nums: List[int], val: int) -> int: l, r = 0, len(nums) - 1 while l return l Common Mistakes Modifying the list while iterating with for x in nums plus remove or pop — this changes indices and skips elements. Returning the modified list instead of the new length . Trying to maintain order with an algorithm designed to minimize writes (e.g., two-pointer-swap) without noting that order...

Python Project: AI Based Assignment Completer

Python Project: AI-Based Assignment Completer A small suite of Python scripts that generate C programs from prompts, create outputs and collect code into a .docx file. 1. File 1 — generator (generate C files) Notes: Replace the API key placeholder on the line where openai.api_key is set with your own key, or set openai.api_key elsewhere in your environment. Create a prompt.txt file in the same directory with one question per line. Create a folder named programms in the same directory — generated C files will be placed there. The Python code (unchanged): import os import openai class Ai: number=0 def automatedquery(self, query): '''this f(x) returns the responce generated by cahtgpt''' openai.api_key = "Your Api Key Here!" response = openai.Completion.create( model="text-davinci-003", prompt=query, ...