🔷 Day 28- 30DaysChallenge(Leetcode Problem): 🌟 Problem: Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array. 🧠Solution: class Solution: def splitArray(self, nums: list[int], k: int) -> int: low, high = max(nums), sum(nums) def ok(x): cnt, curr = 1, 0 for v in nums: if curr + v <= x: curr += v else: cnt += 1 curr = v if cnt > k: return False return True while low < high: mid = (low + high) // 2 if ok(mid): high = mid else: low = mid + 1 return low #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
"Minimize largest sum of subarray split in 30DaysChallenge"
More Relevant Posts
-
🔷 Day 20- 30DaysChallenge(Leetcode Problem): Merge Sorted Array 🌟 Problem: You are given two integer arrays, nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2, respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. 🧠Solution: class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: tmp_nums1 = nums1[:m] # copy the non zero elements of nums1 p1 = 0 p2 = 0 for p in range(n + m): if p2 >= n or (p1 < m and tmp_nums1[p1] <= nums2[p2]): nums1[p] = tmp_nums1[p1] p1 += 1 else: nums1[p] = nums2[p2] p2 += 1 #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
To view or add a comment, sign in
-
🔷 Day 22- 30DaysChallenge(Leetcode Problem): Non-overlapping Intervals 🌟 Problem: Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping. 🧠Solution: class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort() count = 0 for i in range(1, len(intervals)): if intervals[i][0] < intervals[i-1][1]: if intervals[i][1] < intervals[i-1][1]: intervals[i-1] = intervals[i] else: intervals[i] = intervals[i-1] count += 1 return count #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
To view or add a comment, sign in
-
🔷 Day 23- 30DaysChallenge(Leetcode Problem): Sort Vowels in a String 🌟 Problem: Given a 0-indexed string s, permute s to get a new string t such that: All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i]. The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j]. Return the resulting string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. 🧠Solution: class Solution: def sortVowels(self, s: str) -> str: stack = [] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} for x in s: if x in vowels: stack.append(x) stack.sort(reverse=True) res = '' for x in s: if x in vowels: res += stack.pop() else: res += x return res #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
To view or add a comment, sign in
-
🔷 Day 27- 30DaysChallenge(Leetcode Problem): Special Binary String 🌟 Problem: Special binary strings are binary strings with the following two properties: The number of 0's is equal to the number of 1's. Every prefix of the binary string has at least as many 1's as 0's. You are given a special binary string s. A move consists of choosing two consecutive, non-empty, special substrings of s and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return the lexicographically largest resulting string possible after applying the mentioned operations on the string. 🧠Solution: class Solution: def makeLargestSpecial(self, s: str) -> str: subs, bal, start = [], 0, 0 for i, ch in enumerate(s): bal += 1 if ch == '1' else -1 if bal == 0: mid = self.makeLargestSpecial(s[start + 1:i]) subs.append('1' + mid + '0') start = i+1 subs.sort(reverse = True) return ''.join(subs) #DSA #Python #CodingChallenge #30dayschallenge #Leetcode #SoftwareEngineer
To view or add a comment, sign in
-
📅 Day 96 Summary: K Closest Points to Origin On Day 96, you successfully solved a medium-difficulty problem titled "K Closest Points to Origin" on GeeksforGeeks. 🎯 Problem Statement Goal: Given an array of points [x, y] and an integer K, return the K closest points to the origin (0,0). 🧠 Solution Approach (Max Heap / Priority Queue) The visible Python code indicates you used a Max Heap (specifically, Python's heapq module combined with negative values to simulate a Max Heap) to maintain the K closest points found so far. Calculate Squared Distance: A helper function squaredDis calculates x2 +y2 for each point. Maintain a Max Heap of Size K: The loop iterates through all points in the input. For each point, it pushes the pair (−distance,point) onto the maxHeap. The negative distance is used because Python's heapq is a Min Heap, and negating the value makes it behave like a Max Heap based on magnitude (the largest negative number is the smallest value, so the point with the largest distance among the K is at the top). If the heap size exceeds K, the element at the top (which is the point with the largest distance among the current K points) is removed using heappop. Final Result: After processing all points, the heap contains the K points with the smallest distances. The final step is to pop all elements from the heap and extract the point coordinates.
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 83 Problem: Minimum Possible Length of Original String from Concatenated Anagrams 🔡✨ This was an elegant string manipulation and frequency-matching problem — a beautiful blend of observation and brute-force validation. 🧠 Problem Summary: You are given a string s, known to be a concatenation of anagrams of some original string t. The task is to determine the minimum possible length of t. ✅ Each substring of length len(t) should contain exactly the same frequency of characters. ✅ The string s can thus be divided into equal-length chunks, all being anagrams of t. ✅ The goal is to find the smallest such length that satisfies this property. ⚙️ My Approach: 1️⃣ Iterate through all divisors i of n = len(s) — potential lengths of t. 2️⃣ For each possible i, check if the string can be divided into equal parts where each part has identical character frequencies. 3️⃣ Use hash maps to store frequency counts and compare each block. 4️⃣ Return the smallest i that satisfies the condition. 📈 Complexity: Time: O(n²) → Checking frequency for each valid divisor. Space: O(k) → For storing character counts per block. ✨ Key Takeaway: When tackling anagram-based problems, frequency comparison is your strongest ally. Instead of guessing patterns, rely on structure and repetition to reveal the hidden base string. 🔍 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #StringManipulation #Anagram #Python #CodingChallenge #InterviewPrep #EfficientCode #HashMap #DataStructures #TechCommunity #CodeEveryday #LearningByBuilding
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 101 Problem: Maximum Number of Operations on Binary String ⚙️💡 This problem was an elegant mix of string traversal and logical counting, where understanding the movement of '1's relative to '0's was key to finding the optimal number of operations. 🧠 Problem Summary: You are given a binary string s. You can repeatedly perform the following operation: Choose an index i where s[i] == '1' and s[i + 1] == '0'. Move '1' right until it reaches the end or another '1'. Your goal → Return the maximum number of operations that can be performed. ⚙️ My Approach: 1️⃣ Traverse the string from left to right. 2️⃣ Maintain two counters: ones → counts the number of '1's encountered so far. res → stores the total number of operations. 3️⃣ Every time a '0' is found after some '1's, we can perform operations equal to the number of '1's seen so far. 4️⃣ Continue counting consecutive zeros and repeat the process. 💡 Why This Works: Each '1' can “influence” all the zeros that appear after it — moving right across them. Hence, for every block of zeros, we add all previously counted ones to our result. 📈 Complexity Analysis: Time Complexity: O(n) → Single pass through the string. Space Complexity: O(1) → Constant extra space. ✨ Key Takeaway: Sometimes, all it takes is counting relationships instead of simulating moves — a simple greedy insight leading to an optimal O(n) solution. ⚡ 🔖 #DSA #100DaysOfCode #Day101 #LeetCode #ProblemSolving #GreedyAlgorithm #StringManipulation #Python #CodingChallenge #TechCommunity #EfficientCode #LearnByDoing
To view or add a comment, sign in
-
-
#120DaysChallenge #Day_18 #Concept: list comprehension list comprehension in Python is a concise and efficient way to create new lists by applying an expression to each item in an existing iterable, optionally including conditional filtering, all within a single line of code. #syntax ----->[expr for var in collection/range] ex1: 🔸 Not using list comprehension a=["codegnan","python","course"] b=str(a) print(b.upper()) output: ['CODEGNAN', 'PYTHON', 'COURSE'] 🔸 Using list comprehension a=[i.upper() for i in a] print(a) output: ['CODEGNAN', 'PYTHON', 'COURSE'] ex2 🔸 a=[1,2,4,5,6,8,12,13] b=[i**2 for i in a] b=[i*2 for i in a] b=[pow(i,2) for i in a] print(b) output: [1, 4, 16, 25, 36, 64, 144, 169] ex3 🔸 if-else usage in list comprehension a=[i*i if i%2==0 else i*5 for i in range(31)] print(a) output: [0, 5, 4, 15, 16, 25, 36, 35, 64, 45, 100, 55, 144, 65, 196, 75, 256, 85, 324, 95, 400, 105, 484, 115, 576, 125, 676, 135, 784, 145, 900] ex4 🔸 a=[1,2,3,4,5] b=[5,4,3,2,1] c=[a[i]+b[i] for i in range(len(a))] c=[a[i]+b[i] for i in range(5)] print(c) output: [6, 6, 6, 6, 6] Codegnan! Saketh Kallepu sir! Uppugundla Sairam sir! Pooja Chinthakayala mam!
To view or add a comment, sign in
-
🚀 #Day9 of "Prompt Patterns for Developers": Unlocking the Power of Chain of Thought! 🚀 Today, we explored Chain of Thought (CoT) prompting, a game-changer for getting LLMs to think like us – step-by-step. The Concept: CoT prompting guides LLMs to break down complex problems into manageable, sequential steps, revealing their reasoning process. This is incredibly valuable for tasks requiring logical deduction, like code debugging or complex problem-solving. It's like asking a colleague to "show their work" rather than just giving an answer. 💡 Practice: Debugging with Step-by-Step Reasoning 💡 We put CoT into action by asking an LLM to debug a Python stacktrace with the explicit instruction: "Explain step by step." The difference in the output was remarkable – instead of just a solution, we got a clear, logical walkthrough of the error's origin and resolution. 🎯 Prompt Example: Debugging a Python Stacktrace Analyze the following Python stacktrace and explain, step-by-step, the likely cause of the error and how to fix it. Python Stacktrace: Traceback (most recent call last): File "main.py", line 10, in <module> result = divide(10, 0) File "main.py", line 5, in divide return a / b ZeroDivisionError: division by zero Explain step by step: This prompt clearly sets the context, provides the problem (the stacktrace), and most importantly, explicitly requests a "step-by-step" explanation. This small addition significantly enhances the quality and usefulness of the LLM's response. How do you use step-by-step reasoning in your own problem-solving? Share your insights below! #PromptEngineering #AIforDevelopers #LLMs #ChainOfThought #Debugging #Python #TechTips #DeveloperLife #MachineLearning
To view or add a comment, sign in
-
-
How Pydantic AI Turned My Chaotic Data Into a Super‑Smart Python Model 🤖 I was juggling a legacy API that returned nested JSON like a tangled ball of yarn—lists inside dicts, optional fields, and a few hidden “type‑mismatch” bugs that broke the whole pipeline. Every time I wrote a new class, I added manual checks, and the codebase grew into a nightmare of try/except blocks. Enter Pydantic AI. I fed it a single example payload, and it instantly generated a hierarchy of BaseModel classes with proper type hints, default values, and validators for the edge cases. The next day, the same API response passed through the model without a single runtime error, and the auto‑generated docs showed exactly what each field meant. Adding a new optional field? Just update the example and let Pydantic AI regenerate—no more hand‑rolled parsing logic. Now my services serialize, deserialize, and validate data in one line, and the code reads like a story instead of a maze. #Python #PydanticAI #DataValidation
To view or add a comment, sign in
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