Day 6: š«” [Leet Code] Problem: š§© LeetCode Problem: Remove Element (In-Place) Today I solved a classic array problem that testsĀ in-place manipulation and pointer logic. š¹ Problem Statement Given an integer arrayĀ numsĀ and an integerĀ val, remove all occurrences ofĀ valĀ in-place. The order of elements may be changed. ReturnĀ k, the number of elements not equal toĀ val, such that: The firstĀ kĀ elements ofĀ numsĀ contain valuesĀ not equalĀ toĀ val Elements beyondĀ kĀ do not matter. š§ Key Understanding No extra array should be used The array must be modifiedĀ in-place Only the firstĀ kĀ elements matter Time complexity should be efficient š” Approach Used (Two-Pointer Technique) Use a pointerĀ kĀ to track the position of valid elements Traverse the array using indexĀ i IfĀ nums[i] != val, place it at positionĀ kĀ and incrementĀ k Finally, returnĀ k š§Ŗ Python Solution class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0 n = len(nums) for i in range(n): if nums[i] != val: nums[k] = nums[i] k += 1 return k ā±ļø Complexity Analysis Time Complexity:Ā O(n) Space Complexity:Ā O(1). LeetCode #Python #DSA #InterviewPreparation #ProblemSolving #Coding
Remove Element from Array in Place with Two-Pointer Technique
More Relevant Posts
-
Why manually check Fire Ratings when the model can do it for you?Ā I wrote a Python script to automate this check.It finds every door in the project.It identifies the "Host" wall for each door.It pulls the Fire Rating from the Wall Type and pushes it directly to the Door's parameters.In the video, you can see it syncing the data instantly. If the wall changes, I just run the script again. Zero manual entry. #RevitAPI #Python#Day 6-100Days Challenge
To view or add a comment, sign in
-
# The Python Range Object # Arguments: <start number>, <end number - don't include>, <steps> # <steps> defaults to incrementing by 1 (no skipping numbers) # <steps> can be a negative number to decrement values. # When using negative steps, the start number should be larger #Ā Ā than the end number. range(3, 23, 2) # result: 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 # This is creating a number factory that starts at 3, #Ā Ā and returns incremental numbers according to the #Ā Ā <steps> value. # In this case, after returning the initial start value of 3, #Ā Ā it will return 5, then 7, then 9, and so on, until 21. # It excludes the end number from the count. # Frequently, another object is used with range, to process #Ā Ā the entire returned number set. # For example, the "List" object can be used to convert the range #Ā Ā of numbers into an equivalent list of numbers. list(range(3, 15, 2)) # result: [3, 5, 7, 9, 11, 13]
To view or add a comment, sign in
-
When you start writing a system, the easiest thing to say is, āI'll tidy up the code laterā In practice, that ālaterā almost never comes. The result is a lot of mess and bugs that could have been avoided. In the system I'm currently building in Python, I'm using two tools that help me solve this from the outset: Ruff - a tool that runs on the code and automatically formats it (consistent line length, spacing, brackets, etc) and catches problems before they become bugs. Two useful rules: 1. builtin variable shadowing* Checks for variable (and function) assignments that use the same names as builtins 2. Mutable argument default** Checks for uses of mutable objects as function argument defaults. There are similar tools for every programming language called linters.*** Pyright - static type checker: Errors that would occur during runtime are caught already during writing. The experience of seeing a type error before I run the code saves a lot of debugging time. The autocompletion and insights it provides make it easier to work with complex code. These two tools don't make the code perfect, but they allow me to catch problems earlier and write more consistently. This is much more worthwhile than trying to āfix it later.ā relevant links: *https://lnkd.in/e5zNv6UZ **https://lnkd.in/ecg-fwT9 ***https://lnkd.in/eV35fKWU
To view or add a comment, sign in
-
-
Solved LeetCode 944 ā Delete Columns to Make Sorted š§ š This problem looks simple at first, but itās a great reminder that clear thinking beats complex logic. š Problem in short: - Youāre given multiple strings of equal length. Imagine them stacked one below another, forming a grid. Your task is to delete columns that are NOT lexicographically sorted from top to bottom and return how many such columns exist. š§ How I approached it: 1ļøā£ First, I visualized the strings as a table where: - Each row is a string - Each column contains characters from all strings at that position 2ļøā£ Then, I checked each column independently: - Start from the top row - Compare every character with the one directly below it 3ļøā£ If at any point: - The upper character is greater than the one below ā That column is not sorted 4ļøā£ The moment a column fails this condition: - I mark it for deletion - Move on to the next column (no need to check further for that one) 5ļøā£ Finally, I count how many columns were marked for deletion. ⨠Key takeaway - You donāt always need advanced data structures. - Sometimes, a simple comparison + clean iteration is all it takes. #LeetCode #DSA #ProblemSolving #Python #LearningInPublic #Consistency
To view or add a comment, sign in
-
-
š ššš² š (ššÆšš§š¢š§š ) šØš šš² šš-ššš² šš²šš”šØš§ šš”šš„š„šš§š š ā šššš & šš¢š¦š ššš§šš„š¢š§š In todayās evening session, I focused on date and time handling ā a critical skill for logging, analytics, scheduling, and reporting. Pythonās datetime module makes working with dates and times straightforward. š¹ šš”šš š ššØšÆšš«šš ššØššš² ā Getting Current Date & Time from datetime import datetime now = datetime.now() print(now) ā Working with Dates from datetime import date today = date.today() print(today) ā Formatting Dates formatted = now.strftime("%Y-%m-%d %H:%M:%S") print(formatted) ā Date Arithmetic with timedelta from datetime import timedelta future_date = today + timedelta(days=7) print(future_date) ā Difference Between Dates start_date = date(2024, 1, 1) end_date = date.today() difference = end_date - start_date print(difference.days) šÆ ššš² ššš¤ššš°šš² Date and time handling is essential for real-world applications like reports, logs, and automation. Mastering datetime and timedelta makes time-based logic much easier. ā Day 8 Completed ššØš¦šØš«š«šØš°: ššš² š (ššØš«š§š¢š§š ) ā ššš ššš¬š¢šš¬ (šš„šš¬š¬šš¬ & ššš£šššš¬) Letās keep moving #Python #DateTime #15DaysOfPython #LearningInPublic #Programming
To view or add a comment, sign in
-
š Day 53 of #100DaysOfCode ā Making Array Sum Divisible by K Hey everyone! š Todayās challenge focused on a smart math-based optimization problem where the goal was to make the sum of an array divisible by a given number k using the minimum number of operations. šØš» What I practiced today: ā Understanding modulo (%) operations deeply ā Translating a problem into a simple mathematical observation ā Optimizing brute-force thinking into an O(n) solution ā Writing clean and minimal Python code š Todayās Task: ā Given an integer array nums and an integer k ā In one operation, decrement any element by 1 ā Find the minimum operations required so that sum(nums) is divisible by k š§ Key Insight: If the sum of the array is S, then the minimum number of operations required is simply: S % k Because each operation reduces the sum by 1. š” Example: Input: nums = [3, 9, 7], k = 5 Sum = 19 ā 19 % 5 = 4 Output: 4 ⨠Key Takeaway: Sometimes the best solution isnāt complex logic or loops ā itās recognizing a simple mathematical pattern. Mastering such observations can drastically reduce code complexity and runtime. #100DaysOfCode #Day53 #Python #LeetCode #ProblemSolving #MathInProgramming #CodingJourney #DSA #CleanCode
To view or add a comment, sign in
-
-
Iāve been working on a small Python library, stat-guard, and I just published v0.2.0 on PyPI. pip install stat-guard The idea is simple: Most statistical mistakes donāt come from wrong formulas. They come from bad data and violated assumptions that go unnoticed until after results are shipped. Things like: duplicated users counted multiple times users leaking across control and treatment sample sizes too small to justify comparisons extreme imbalance between groups metrics with zero variance stat-guard is a pre-analysis validation layer. You run it before doing any stats, and it tells you whether your data violates basic assumptions that would invalidate the analysis. It does not run hypothesis tests. It does not fix data. It only makes assumptions explicit and enforceable. Right now itās intentionally minimal: ā one validate() entry point ā deterministic rules ā clear errors vs warnings ā usable in notebooks or pipelines This is still early and opinionated, but I wanted to get it out, document it clearly, and get feedback from people who care about experiment quality. PyPI: https://lnkd.in/dARZ2XS3 GitHub: https://lnkd.in/dU-5-xsk If youāve ever been burned by āstatistically validā results that later turned out to be based on broken assumptions, this might be useful ā or at least a starting point. #statistics #datascience #experimentation #python #opensource
To view or add a comment, sign in
-
-
Practised Python list manipulation methods to work with dynamic data efficiently. Used methods like append(), insert(), and extend() to add elements in different ways. Understood the difference between reference copy and shallow copy using copy(). Worked with pop() and remove() to delete elements by index and value. Implemented logic to remove duplicates, find item positions using index(), and frequency using count(). These exercises improved my understanding of list behavior, memory handling, and data operations. #Python #Lists #DataStructures #PythonBasics #ListMethods #LearningJourney
To view or add a comment, sign in
-
Not all attributes in Python should be plain data @propertyĀ lets you expose a method like an attribute: compute values on access, control read/write, keep a clean API without breaking callers. Benefits: 1/ Encapsulation ā hide implementation, validate on set, control access. 2/ Computed attributes ā derive values on-the-fly (no stored redundant state). 3/ Backward compatibility & readability ā switch a public attribute to a property without changing callers. 4/ Clear intent ā callers readĀ obj.valueĀ instead ofĀ obj.get_value()Ā when itās conceptually an attribute.
To view or add a comment, sign in
-
-
Observation.org just released `euring`, an open-source Python library and CLI for working with EURING ringing and recovery records. It lets you decode, validate and convert records, export records and code tables as JSON, and work with stable, machine-readable field keys in your software and data pipelines. Built for anyone developing or maintaining software around bird ringing data. Link:Ā https://lnkd.in/ezzfS-sv EURING Codes are published and maintained by EURING.
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development