Leetcode with dani – Telegram
Leetcode with dani
1.31K subscribers
196 photos
14 videos
56 files
240 links
Join us and let's tackle leet code questions together: improve your problem-solving skills
Preparing for coding interviews
learning new algorithms and data structures
connect with other coding enthusiasts
Download Telegram
Leetcode with dani
Let’s tackle "Contains Duplicate II"! Day 1 Q 2 Problem Statement: Given an integer array nums and an integer k, return true if there are two distinct indices i and j such that: nums[i] == nums[j] abs(i - j) <= k Otherwise, return false. Examples to Get…
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
myset = set()
l = 0
for i in range(len(nums)):
while(i-l>k):
myset.remove(nums[l])
l+=1
if nums[i] in myset:
return True
myset.add(nums[i])
return False
Understanding Time Complexity with Simple Examples

Hey everyone! 👋
Today, we’re going to break down Time Complexity in the simplest way possible. Whether you're a beginner or just need a refresher, this guide will help you understand how algorithms perform as input sizes grow. Let’s dive in! 🚀

What is Time Complexity?
Time Complexity is a way to describe how the runtime of an algorithm grows as the input size increases. It helps us compare algorithms and predict their performance without running them on actual machines.

We use Big-O Notation (like O(n), O(log n), etc.) to express time complexity. It tells us the upper bound of an algorithm's runtime in the worst-case scenario.

Real-Life Example: Finding a Pen in a Classroom
Imagine you’re in a classroom with 100 students, and you’ve given your pen to one of them. You need to find it! Here’s how different approaches work:

O(n²) Approach:

Ask the first student if they have the pen.
Also, ask them about the other 99 students.
Repeat this for every student.
This is inefficient and takes a lot of time.

O(n) Approach:

Go to each student one by one and ask if they have the pen.
This is linear and much better than O(n²).

O(log n) Approach:

Divide the class into two groups.
Ask: “Is the pen on the left or right side?”
Repeat this process until you find the student with the pen.
This is super efficient!

Key Points About Time Complexity

It’s Not Actual Runtime:

Time Complexity doesn’t measure the exact time an algorithm takes to run.
Instead, it measures how the runtime grows as the input size increases.
Why Use Big-O?

It helps us compare algorithms independent of hardware or programming language.
For example, O(n) will always be faster than O(n²) for large inputs.
Examples to Understand Time Complexity

Example 1: Constant Time - O(1)
print("Hello World")
Explanation: The code runs in constant time because it prints "Hello World" only once, no matter the input size.
Time Complexity: O(1)

Example 2: Linear Time - O(n)
n = 8
for i in range(1, n + 1):
print("Hello World !!!")
Explanation: The code prints "Hello World !!!" n times. As n grows, the runtime grows linearly.
Time Complexity: O(n)

Example 3: Logarithmic Time - O(log n)

n = 8
for i in range(1, n + 1, 2):
print("Hello World !!!")
Explanation: The loop runs logarithmically because it skips half the steps each time.
Time Complexity: O(log n)

Example 4: Polynomial Time - O(n²)
n = 3
m = 3
arr = [[3, 2, 7], [2, 6, 8], [5, 1, 9]]
sum = 0

for i in range(n):
for j in range(m):
sum += arr[i][j]
print(sum)
Explanation: The code uses nested loops to sum all elements in a 2D array.
Time Complexity: O(n * m)

How to Compare Algorithms?

To compare algorithms, we focus on:

Growth Rate: How does the runtime grow as input size increases?
Big-O Notation: Use it to express the upper bound of runtime.
For example:
O(1) < O(log n) < O(n) < O(n²) < O(2ⁿ)

Why Does Time Complexity Matter?

Efficiency: Helps us choose the best algorithm for large inputs.
Scalability: Ensures our code performs well as data grows.
Optimization: Guides us in writing faster and more efficient programs.
Final Thoughts
Understanding Time Complexity is crucial for writing efficient algorithms. By using Big-O Notation, we can predict how our code will perform and make better decisions when solving problems.

Keep practicing, and soon you’ll be a pro at analyzing algorithms! 💪

Got questions? Drop them in the comments below! Let’s learn together. 🚀

Source: GeeksforGeeks and DeepSeek.
Share to ur Friends
Leetcode with dani
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: myset = set() l = 0 for i in range(len(nums)): while(i-l>k): myset.remove(nums[l]) l+=1 …
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:

num_indices = {}
for i, num in enumerate(nums):
if num in num_indices and i - num_indices[num] <= k:
return True
num_indices[num] = i

return False
👍2
Check this Website it has good road map to practice neetcode questions

https://neetcode.io/roadmap
42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:


Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9


Constraints:

n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105

who wants to try answering this question? Don’t worry, it’s not too scary! 😄 Try
🤔2
leetcode new Feautre
u can invite ur friends to do questions together
Leetcode with dani
42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above…
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
left = 0
right = len(height) - 1
left_max = right_max = 0
total = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
total += left_max - height[left]
left += 1
else:
if height[right] >= right_max:
right_max = height[right]
else:
total += right_max - height[right]
right -= 1
return total
Day 2 Q1
31. Next Permutation

Medium
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.

For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

For example, the next permutation of arr = [1,2,3] is [1,3,2].
Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
Given an array of integers nums, find the next permutation of nums.

The replacement must be in place and use only constant extra memory.



Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:

Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:

Input: nums = [1,1,5]
Output: [1,5,1]

Topics : Two pointer and Array
Submit
👍1
Leetcode with dani
Day 2 Q1 31. Next Permutation Medium A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3…
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
r = len(nums)-1
while r>=1:
if nums[r] >nums[r-1]:
if r+1<len(nums) and nums[r+1] >nums[r-1]:
k = 2
while (r+k<len(nums) and nums[r+k] >nums[r-1]):
k+=1
k-=1
nums[r+k],nums[r-1]=nums[r-1],nums[r+k]
else:
nums[r],nums[r-1]=nums[r-1],nums[r]
break
else:
r -= 1
l = len(nums)-1
while l>r:
if nums[l] <nums[r]:
nums[l],nums[r] = nums[r],nums[l]
l-=1
r+=1
Day2 Q2
15. 3Sum
Medium
Hint
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.



Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
try
Day2 Q3
167. Two Sum II - Input Array Is Sorted
Medium

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.



Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].


Constraints:

2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution.
Try
Leetcode with dani
Day2 Q2 15. 3Sum Medium Hint Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. …
To solve this problem, we need to find all unique triplets in an array that sum to zero. The solution must avoid duplicate triplets and efficiently handle the input constraints.

Approach
Sort the Array: Sorting helps in efficiently finding triplets and avoiding duplicates by allowing us to skip over identical elements.

Iterate with a Fixed Element: For each element in the array (up to the third last element), treat it as the first element of the triplet.

Two-Pointer Technique: Use two pointers (left and right) to find the remaining two elements such that their sum with the fixed element equals zero. Adjust the pointers based on whether the current sum is less than or greater than zero.

Skip Duplicates: After finding a valid triplet, skip over any subsequent duplicate elements to avoid adding the same triplet multiple times.

def threeSum(nums):
res = []
nums.sort()
n = len(nums)
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # Skip duplicate elements for the first element of the triplet
left, right = i + 1, n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if current_sum == 0:
res.append([nums[i], nums[left], nums[right]])
# Skip duplicates for the second element
while left < right and nums[left] == nums[left + 1]:
left += 1
# Skip duplicates for the third element
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif current_sum < 0:
left += 1
else:
right -= 1
return res

Explanation
Sorting the Array: This step ensures that any duplicates are adjacent, making it easier to skip them.

Fixed Element Iteration: For each element in the array (excluding the last two to ensure there are elements left for the other two pointers), we check if it's a duplicate of the previous element. If it is, we skip it to avoid duplicate triplets.

Two-Pointer Technique: The left pointer starts right after the fixed element, and the right pointer starts at the end of the array. Depending on the sum of the three elements, we adjust the pointers inward:

If the sum is zero, we add the triplet to the result and move both pointers inward, skipping any duplicates.

If the sum is less than zero, we move the left pointer to the right to increase the sum.

If the sum is greater than zero, we move the right pointer to the left to decrease the sum.

Skipping Duplicates: After finding a valid triplet, we move the left pointer past all duplicates of the current left element and the right pointer past all duplicates of the current right element to avoid adding the same triplet again.

This approach efficiently finds all unique triplets with a time complexity of O(n^2), which is optimal for the given problem constraints.
Easy Problem: Two Sum (LeetCode #1)
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Example:
Input: nums = [2, 7, 11, 15], target = 9  
Output: [0, 1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].


Constraints:
- 2 <= nums.length <= 10^4
- -10^9 <= nums[i] <= 10^9
- Only one valid answer exists.

Practice here: LeetCode

---

Medium Problem: Maximum Subarray (LeetCode #53)
Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example:
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]  
Output: 6
Explanation: The subarray [4, -1, 2, 1] has the largest sum = 6.


Constraints:
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4

Hint: Use Kadane's Algorithm (Greedy/Sliding Window approach) to solve this efficiently!

Practice here: LeetCode

---

Medium Problem: Valid Parentheses (LeetCode #20)
Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.

An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

Example:
Input: s = "()[]{}"  
Output: true

Input: s = "(]"
Output: false


Constraints:
- 1 <= s.length <= 10^4
- s consists of parentheses only '()[]{}'.

Hint: Use a stack to ensure proper matching of parentheses!

Practice here: LeetCode
Problem: Find Words That Can Be Formed by Characters
Problem Link:
You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words.

Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings "cat" and "hat" can be formed using the characters of chars, so the total length is 3 + 3 = 6.

Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: The strings "hello" and "world" can be formed using the characters of chars, so the total length is 5 + 5 = 10.

Constraints:

1 <= words.length <= 1000

1 <= words[i].length, chars.length <= 100

words[i] and chars consist of lowercase English letters.

Challenge: Can you solve this problem efficiently? Try it out and share your approach!
Day 4 Q 1
1. Insert Delete GetRandom O(1)
Link
Problem: Design a data structure that supports insert, remove, and getRandom operations in average O(1) time.
Key Points:

Use a dynamic array to store elements for O(1) random access.

Pair it with a hash map to track element indices for O(1) insertion/deletion.

For removal, swap the target element with the last element in the array to avoid shifting.
Example:

Insert 1 → [1]. Insert 2 → [1,2]. Remove 1 → [2]. getRandom() returns 2.

Day 4 Q 2
2. Find Players With Zero or One Losses
Link
Problem: Given match outcomes as [winner, loser], return two lists: players with 0 losses and those with 1 loss, sorted in ascending order.
Key Approach:

Use a hash map to count losses for each player.

Track all players (including winners with 0 losses).

Filter and sort results based on loss counts (0 or 1).
Example:
Input: [[1,3],[2,1],[4,2],[5,2]]
Output: [[4,5], [1,3]]
(Players 4,5 never lost; 1,3 lost once)

Day 4 Q 3
3. Shuffle String
Link
Problem: Reconstruct a string using an index array. For s = "abc" and indices = [0,2,1], return "acb".
Approach:

Create a result array of the same length as s.

Place each character s[i] at result[indices[i]].

Convert the array to a string.
Example:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
👍1
https://news.1rj.ru/str/+axQMvWILZ505Yjlk
Check this channel; it's better to share good resources I find in a separate channel rather than posting them here. I post new resources that teach you full stack development, including HTML, CSS, JavaScript, Bootstrap, Node.js, React, Git, MongoDB, APIs, and more
3👍1
Day 5
🗓 Daily Challenge #1
🧩 Build Array from Permutation
Given an array nums, build a new array ans where ans[i] = nums[nums[i]] for every index i.
Can you solve it without extra space? (Hint: Think modulo!)

🔗 Problem Link:
📌 Difficulty: Easy
🏷 Tags: #Array #InPlace

💡 Let’s see your optimized solutions!
👉 Drop your approach in the comments!

📊 Problem Breakdown #2
🔄 Matrix Rotation Check
Given two n x n matrices, determine if one can be obtained by rotating the other 90°, 180°, or 270°.
How would you efficiently check all possible rotations?

🔗 Problem Link:
📌 Difficulty: Medium
🏷 Tags: #Matrix #Transpose

🤔 Think about transpose + reverse vs. brute force. Which is better?
👉 Share your code snippets!

🚀 Advanced Problem Alert!
🔢 Tuple with Same Product
Find the number of tuples (a, b, c, d) such that a*b = c*d where all elements are distinct.
Can you avoid an O(n⁴) solution? (Hint: Hash maps are your friend!)

🔗 Problem Link:
📌 Difficulty: Medium
🏷 Tags: #HashTable #Combinatorics

💥 Challenge: Optimize for large arrays!
👉 Post your best time complexity in the comments!
👍3
Leetcode with dani
Day 4 Q 1 1. Insert Delete GetRandom O(1) Link Problem: Design a data structure that supports insert, remove, and getRandom operations in average O(1) time. Key Points: Use a dynamic array to store elements for O(1) random access. Pair it with a hash map…
🌟 Day 4 Coding Challenges: Solutions Explanations 🌟

Welcome to Day 4 of our coding journey! Today, we tackle some exciting problems that challenge our data structure skills. Let’s dive in!

---

🏗 Q1: Insert Delete GetRandom O(1)

Problem Statement:

Design a data structure that supports insert, remove, and getRandom operations in average O(1) time.

💡 Solution:

To achieve O(1) time complexity for all operations, we can employ a clever combination of a dynamic array and a hash map:

1. Dynamic Array: Stores elements, allowing for O(1) random access.

2. Hash Map: Tracks the indices of elements for O(1) insertion and deletion.

3. Removal Strategy: Swap the target element with the last element to avoid shifting.

🔍 Python Implementation:

import random

class RandomizedSet:
def __init__(self):
self.array = [] # For O(1) random access
self.indices = {} # Maps elements to their indices

def insert(self, val: int) -> bool:
if val in self.indices:
return False # Element already exists
self.indices[val] = len(self.array)
self.array.append(val)
return True

def remove(self, val: int) -> bool:
if val not in self.indices:
return False # Element does not exist
index = self.indices[val]
last_element = self.array[-1]

# Swap and remove
self.array[index] = last_element
self.indices[last_element] = index
self.array.pop()
del self.indices[val]
return True

def getRandom(self) -> int:
return random.choice(self.array)


🚀 Example Usage:

randomizedSet = RandomizedSet()
print(randomizedSet.insert(1)) # True
print(randomizedSet.remove(2)) # False
print(randomizedSet.insert(2)) # True
print(randomizedSet.getRandom()) # Either 1 or 2
print(randomizedSet.remove(1)) # True
print(randomizedSet.insert(2)) # False
print(randomizedSet.getRandom()) # 2


---

🏆 Q2: Find Players With Zero or One Losses

Problem Statement:

Given match outcomes as [[winner, loser]], return two sorted lists:

1. Players with 0 losses.

2. Players with exactly 1 loss.

💡 Solution:

We can efficiently solve this using:

• A hash map to count losses.

• A set to track all players.

🔍 Python Implementation:

def findWinners(matches):
loss_counts = {}
players = set()

for winner, loser in matches:
players.add(winner)
players.add(loser)
loss_counts[loser] = loss_counts.get(loser, 0) + 1

zero_losses = sorted([player for player in players if loss_counts.get(player, 0) == 0])
one_loss = sorted([player for player in players if loss_counts.get(player, 0) == 1])

return [zero_losses, one_loss]


🚀 Example Usage:

matches = [[1, 3], [2, 1], [4, 2], [5, 2]]
result = findWinners(matches)
print(result) # Output: [[4, 5], [1, 3]]


---

🔄 Q3: Shuffle String

Problem Statement:

Reconstruct a string using an index array. For s = "abc" and indices = [0, 2, 1], return "acb".

💡 Solution:

We create a result array of the same length as s and place each character at its corresponding index from the indices array.

🔍 Python Implementation:

def restoreString(s, indices):
result = [''] * len(s)
for i, idx in enumerate(indices):
result[idx] = s[i]
return ''.join(result)


🚀 Example Usage:

s = "codeleet"
indices = [4, 5, 6, 7, 0, 2, 1, 3]
result = restoreString(s, indices)
print(result) # Output: "leetcode"
👍5