<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: pythonic_solutions</title>
    <description>The latest articles on Forem by pythonic_solutions (@xyz_pythonic).</description>
    <link>https://forem.com/xyz_pythonic</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F806879%2Fe1e2e04d-d877-4066-b64e-b3db3e2f5819.png</url>
      <title>Forem: pythonic_solutions</title>
      <link>https://forem.com/xyz_pythonic</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/xyz_pythonic"/>
    <language>en</language>
    <item>
      <title>28. Find the Index of the First Occurrence in a String. When To Use find( )</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Tue, 13 May 2025 13:55:17 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/28-find-the-index-of-the-first-occurrence-in-a-string-when-to-use-find--2jg6</link>
      <guid>https://forem.com/xyz_pythonic/28-find-the-index-of-the-first-occurrence-in-a-string-when-to-use-find--2jg6</guid>
      <description>&lt;p&gt;Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: haystack = "sadbutsad", needle = "sad"&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: "sad" occurs at index 0 and 6.&lt;br&gt;
The first occurrence is at index 0, so we return 0.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: haystack = "leetcode", needle = "leeto"&lt;br&gt;
Output: -1&lt;br&gt;
Explanation: "leeto" did not occur in "leetcode", so we return -1.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= haystack.length, needle.length &amp;lt;= 104&lt;br&gt;
haystack and needle consist of only lowercase English characters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution:
    def strStr(self, haystack: str, needle: str) -&amp;gt; int:
        return haystack.find(needle)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The most efficient and Pythonic way to solve this problem would be using Python's built-in string method find(). This method returns the lowest index of the substring needle in the string haystack if found, and -1 if it's not found. It is optimized and much faster than manually iterating through the string.&lt;/p&gt;

&lt;p&gt;Solution using find():&lt;/p&gt;

&lt;p&gt;def strStr(haystack: str, needle: str) -&amp;gt; int:&lt;br&gt;
    return haystack.find(needle)&lt;/p&gt;

&lt;p&gt;Explanation:&lt;br&gt;
haystack.find(needle): This returns the index of the first occurrence of needle in haystack. If needle is not found, it returns -1.&lt;/p&gt;

&lt;p&gt;This solution has a time complexity of O(n), where n is the length of haystack, because find() searches through the string efficiently.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;haystack = "sadbutsad"&lt;br&gt;
needle = "sad"&lt;br&gt;
print(strStr(haystack, needle))  # Output: 0&lt;br&gt;
Explanation:&lt;/p&gt;

&lt;p&gt;The substring "sad" is found at index 0 in the string "sadbutsad", so the result is 0.&lt;/p&gt;

&lt;h1&gt;
  
  
  Example 2:
&lt;/h1&gt;

&lt;p&gt;haystack = "leetcode"&lt;br&gt;
needle = "leeto"&lt;br&gt;
print(strStr(haystack, needle))  Output: -1&lt;br&gt;
Explanation:&lt;/p&gt;

&lt;p&gt;The substring "leeto" is not found in "leetcode", so the result is -1.&lt;/p&gt;

&lt;h4&gt;
  
  
  Why find() is efficient:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;find() is implemented in C behind the scenes, making it much faster and more memory-efficient compared to manually looping through the string.&lt;/li&gt;
&lt;li&gt;It automatically handles the substring search in the most optimized way, which is why it's the preferred method for this task.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  when to use find( )
&lt;/h3&gt;

&lt;p&gt;The find() method is very efficient for searching substrings within a string, but it's important to know when to use it. Below are the scenarios when you should consider using find():&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Searching for a Substring's First Occurrence:
Use find() when you want to locate the first occurrence of a substring within a larger string. It will return the index of the first occurrence or -1 if the substring isn't found.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "sadbutsad"&lt;br&gt;
needle = "sad"&lt;br&gt;
print(haystack.find(needle))   Output: 0&lt;br&gt;
In this case, find() efficiently returns the index of the first occurrence of "sad".&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;When You Don’t Need to Handle Multiple Occurrences:&lt;br&gt;
If you're only interested in the first occurrence of the substring and don’t need to know about subsequent occurrences, find() is a great choice. It returns the first index without needing any loops or extra code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For Simple String Matching:&lt;br&gt;
If you're doing basic string matching where the input strings are relatively small or average in size (i.e., they don’t require complex regular expressions or sophisticated string matching algorithms), find() is perfect.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "hello world"&lt;br&gt;
needle = "world"&lt;br&gt;
index = haystack.find(needle)&lt;br&gt;
print(index)   Output: 6&lt;br&gt;
Here, we want to find the first occurrence of "world" in the string "hello world", which is at index 6.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When You Don’t Need to Worry About Case Sensitivity:
find() is case-sensitive. If you need to do a case-insensitive search, you'd need to convert both strings to lower or upper case before calling find().&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "Hello World"&lt;br&gt;
needle = "hello"&lt;br&gt;
print(haystack.lower().find(needle.lower()))   Output: 0&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;For Strings with Small Lengths (Performance Consideration):
The find() method is generally the fastest approach for substring searching in Python. If you're dealing with relatively small strings or strings that are commonly used in typical programming problems, find() will likely be the most efficient.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When not to use find():&lt;br&gt;
When you need to handle multiple occurrences: If you need to find all occurrences of the substring, find() will&lt;/p&gt;

&lt;p&gt;The find() method in Python is used for searching a substring within a string, and it returns the index of the first occurrence of the substring. If the substring is not found, it returns -1. Here's a breakdown of the cases where find() is useful:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Finding the First Occurrence of a Substring
If you need to find the first occurrence of a substring within a string, find() is ideal. It returns the index of the first match.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If the substring does not exist, find() returns -1.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "hello world"&lt;br&gt;
needle = "world"&lt;br&gt;
index = haystack.find(needle)&lt;br&gt;
print(index)  Output: 6&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Checking if a Substring Exists
You can use find() to check if a substring exists in the main string. If it returns -1, the substring isn't present; otherwise, it returns the index where it is found.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "apple pie"&lt;br&gt;
needle = "pie"&lt;br&gt;
if haystack.find(needle) != -1:&lt;br&gt;
    print("Found!")&lt;br&gt;
else:&lt;br&gt;
    print("Not found!")&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Searching Within a Specific Range (Start and End)
find() allows you to specify optional start and end arguments to limit the search to a specific part of the string. This is useful when you only want to search within a certain slice of the string.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "hello world"&lt;br&gt;
needle = "o"&lt;br&gt;
index = haystack.find(needle, 5)  Start searching from index 5&lt;br&gt;
print(index)   Output: 7 (The first 'o' after index 5 is at position 7)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Case-Sensitive Search
find() is case-sensitive by default. If the case of the substring matters in the search, find() will return the index only if the substring matches exactly in terms of both characters and case.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "Hello World"&lt;br&gt;
needle = "hello"&lt;br&gt;
print(haystack.find(needle))   Output: -1, since case matters&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;When You Don’t Need Regular Expressions&lt;br&gt;
If you just need basic string matching without any advanced pattern matching, find() is the most efficient approach. For more complex matching patterns (like using wildcards or different string structures), you might want to use regular expressions (re module), but find() is sufficient for straightforward substring searches.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For Performance in Small to Medium String Searches&lt;br&gt;
find() is highly optimized for searching within strings and is faster than manually iterating over the string or using more complex methods, especially when dealing with small to medium-sized strings. The performance benefits come from its native implementation in C.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoiding Manual Loops&lt;br&gt;
Using find() avoids the need to manually loop through the string and check each substring. It abstracts the loop logic and provides a simpler, cleaner solution.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;haystack = "find the needle in the haystack"&lt;br&gt;
needle = "needle"&lt;br&gt;
print(haystack.find(needle))  Output: 9, the first occurrence of "needle"&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When You Only Need the First Occurrence
If you're only interested in the first occurrence of the substring, using find() is preferable over using index() (which raises an exception when not found), or writing a loop to find the first occurrence manually.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  When Not to Use find():
&lt;/h4&gt;

&lt;p&gt;Multiple Occurrences: If you need to find all occurrences of a substring in the string, find() is not suitable. You would need a loop or use re.finditer() for multiple occurrences.&lt;/p&gt;

&lt;p&gt;Pattern Matching: For more complex patterns, such as regular expressions (e.g., searching for numbers, special characters), you would want to use the re module instead of find().&lt;/p&gt;

&lt;h4&gt;
  
  
  Summary:
&lt;/h4&gt;

&lt;h4&gt;
  
  
  When to use find():
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;To locate the first occurrence of a substring in a string.&lt;/li&gt;
&lt;li&gt;To check if a substring exists in the string.&lt;/li&gt;
&lt;li&gt;When you don’t need regular expressions for pattern matching.&lt;/li&gt;
&lt;li&gt;When you want a simple and efficient solution for small to medium strings.&lt;/li&gt;
&lt;li&gt;To perform case-sensitive searches.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  When not to use find():
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;When you need to handle multiple occurrences (use findall() or loops).&lt;/li&gt;
&lt;li&gt;When you need advanced pattern matching (use regular expressions).&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>3. Longest Substring Without Repeating Characters Solved</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Tue, 13 May 2025 10:44:33 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/3-longest-substring-without-repeating-characterssolved-40lk</link>
      <guid>https://forem.com/xyz_pythonic/3-longest-substring-without-repeating-characterssolved-40lk</guid>
      <description>&lt;p&gt;Given a string s, find the length of the longest substring without duplicate characters.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: s = "abcabcbb"&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: The answer is "abc", with the length of 3.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: s = "bbbbb"&lt;br&gt;
Output: 1&lt;br&gt;
Explanation: The answer is "b", with the length of 1.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: s = "pwwkew"&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: The answer is "wke", with the length of 3.&lt;br&gt;
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;0 &amp;lt;= s.length &amp;lt;= 5 * 104&lt;br&gt;
s consists of English letters, digits, symbols and spaces.&lt;/p&gt;

&lt;h4&gt;
  
  
  Core Idea (Sliding Window with Two Pointers)
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;We want to find a window in the string that doesn't contain any repeating characters.&lt;/li&gt;
&lt;li&gt;We use two pointers, left and right, to define this window.&lt;/li&gt;
&lt;li&gt;A set (char_set) keeps track of the unique characters in the current window.&lt;/li&gt;
&lt;li&gt;If we find a duplicate, we shrink the window from the left until the duplicate is removed.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def length_of_longest_substring(s: str) -&amp;gt; int:
    char_set = set()
    left = 0
    max_length = 0

    for right in range(len(s)):
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
        char_set.add(s[right])
        max_length = max(max_length, right - left + 1)

    return max_length

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc1imganl8deonsggwqu5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc1imganl8deonsggwqu5.png" alt="Image description" width="800" height="472"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Why It’s Efficient:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Each character is added and removed at most once → O(n)&lt;/li&gt;
&lt;li&gt;Set gives constant time lookup → fast&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  When to Use This Technique:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Use this sliding window + set pattern whenever:&lt;/li&gt;
&lt;li&gt;You need the longest substring/subarray with no repeats&lt;/li&gt;
&lt;li&gt;You need to maintain a dynamic window of valid elements&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Time &amp;amp; Space Complexity:&lt;br&gt;
Type    Value&lt;br&gt;
Time    O(n) (each character is visited at most twice)&lt;br&gt;
Space   O(min(n, m)) where m is the character set size (e.g. 26 lowercase)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>leetcode</category>
      <category>python</category>
    </item>
    <item>
      <title>When to use enumerate( ) and dict ? More Pythonic</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Tue, 13 May 2025 09:12:38 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/when-to-use-enumerate-and-dict--1fah</link>
      <guid>https://forem.com/xyz_pythonic/when-to-use-enumerate-and-dict--1fah</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff9qym4xfssulq8u79qk6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff9qym4xfssulq8u79qk6.png" alt="Image description" width="800" height="438"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;✅ Full Working Examples&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;✅ Need both index and value (enumerate())&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;s = "cat"&lt;br&gt;
for i, ch in enumerate(s):&lt;br&gt;
    print(f"Index: {i}, Character: {ch}")&lt;br&gt;
Output:&lt;/p&gt;

&lt;p&gt;Index: 0, Character: c&lt;br&gt;
Index: 1, Character: a&lt;br&gt;
Index: 2, Character: t&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;✅ Track last occurrence of characters (dict)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;s = "abracadabra"&lt;br&gt;
last_seen = {}&lt;br&gt;
for i, ch in enumerate(s):&lt;br&gt;
    last_seen[ch] = i&lt;br&gt;
print(last_seen)  # {'a': 10, 'b': 8, 'r': 9, 'c': 4, 'd': 6}&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;✅ Fast key-based lookup (dict)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;grades = {"Alice": 95, "Bob": 87, "Charlie": 92}&lt;br&gt;
print(grades["Bob"])  # 87&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;✅ Replacing range(len(...)) with enumerate()&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;numbers = [10, 20, 30]&lt;/p&gt;

&lt;p&gt;Less Pythonic&lt;br&gt;
for i in range(len(numbers)):&lt;br&gt;
    print(i, numbers[i])&lt;/p&gt;

&lt;p&gt;More Pythonic&lt;br&gt;
for i, num in enumerate(numbers):&lt;br&gt;
    print(i, num)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;✅ Mapping relationships (dict)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;capital = {&lt;br&gt;
    "France": "Paris",&lt;br&gt;
    "Japan": "Tokyo",&lt;br&gt;
    "India": "New Delhi"&lt;br&gt;
}&lt;br&gt;
print(capital["Japan"])  # Tokyo&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Check if All Characters Have Equal Number of Occurrences</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Mon, 12 May 2025 14:47:26 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/check-if-all-characters-have-equal-number-of-occurrences-29eo</link>
      <guid>https://forem.com/xyz_pythonic/check-if-all-characters-have-equal-number-of-occurrences-29eo</guid>
      <description>&lt;p&gt;Given a string s, return true if s is a good string, or false otherwise.&lt;/p&gt;

&lt;p&gt;A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: s = "abacbc"&lt;br&gt;
Output: true&lt;br&gt;
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: s = "aaabb"&lt;br&gt;
Output: false&lt;br&gt;
Explanation: The characters that appear in s are 'a' and 'b'.&lt;br&gt;
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= s.length &amp;lt;= 1000&lt;br&gt;
s consists of lowercase English letters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution:
    def areOccurrencesEqual(self, s: str) -&amp;gt; bool:
        from collections import Counter

        freq = Counter(s)
        values = set(freq.values())
        return len(values) == 1

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ Example 1: s = "abacbc"&lt;/p&gt;

&lt;p&gt;freq = Counter(s)         # {'a': 2, 'b': 2, 'c': 2}&lt;br&gt;
freq.values()             # dict_values([2, 2, 2])&lt;br&gt;
set(freq.values())        # {2}&lt;br&gt;
len(set(freq.values()))   # 1 → True ✅&lt;br&gt;
✔️ All characters occur 2 times → set has just one unique value (2)&lt;/p&gt;

&lt;p&gt;❌ Example 2: s = "aaabb"&lt;/p&gt;

&lt;p&gt;freq = Counter(s)         # {'a': 3, 'b': 2}&lt;br&gt;
freq.values()             # dict_values([3, 2])&lt;br&gt;
set(freq.values())        # {2, 3}&lt;br&gt;
len(set(freq.values()))   # 2 → False ❌&lt;br&gt;
✖️ Frequencies differ (3 and 2) → set has two values → return False&lt;/p&gt;

&lt;p&gt;✅ Example 3: s = "xyz"&lt;/p&gt;

&lt;p&gt;freq = Counter(s)         # {'x': 1, 'y': 1, 'z': 1}&lt;br&gt;
freq.values()             # dict_values([1, 1, 1])&lt;br&gt;
set(freq.values())        # {1}&lt;br&gt;
len(set(freq.values()))   # 1 → True ✅&lt;br&gt;
✔️ Each character occurs once → return True&lt;/p&gt;

&lt;p&gt;❌ Example 4: s = "aaabbbcc"&lt;/p&gt;

&lt;p&gt;freq = Counter(s)         # {'a': 3, 'b': 3, 'c': 2}&lt;br&gt;
freq.values()             # dict_values([3, 3, 2])&lt;br&gt;
set(freq.values())        # {2, 3}&lt;br&gt;
len(set(freq.values()))   # 2 → False ❌&lt;br&gt;
✖️ Different counts → return False&lt;/p&gt;

&lt;p&gt;✅ Example 5: s = "a"&lt;/p&gt;

&lt;p&gt;freq = Counter(s)         # {'a': 1}&lt;br&gt;
freq.values()             # dict_values([1])&lt;br&gt;
set(freq.values())        # {1}&lt;br&gt;
len(set(freq.values()))   # 1 → True ✅&lt;br&gt;
✔️ Only one character → always valid → return True&lt;/p&gt;

&lt;p&gt;✅ Time Complexity:&lt;br&gt;
Counter(s):&lt;/p&gt;

&lt;p&gt;This goes through the entire string s once to count frequencies.&lt;/p&gt;

&lt;p&gt;Time: O(n) where n is the length of the string.&lt;/p&gt;

&lt;p&gt;freq.values():&lt;/p&gt;

&lt;p&gt;Extracts the frequency values, which is proportional to the number of unique characters.&lt;/p&gt;

&lt;p&gt;Worst case (e.g., all characters different): O(n)&lt;/p&gt;

&lt;p&gt;set(freq.values()):&lt;/p&gt;

&lt;p&gt;Building a set from up to n frequency values.&lt;/p&gt;

&lt;p&gt;Time: O(k) where k is the number of unique characters (bounded by 26 if only lowercase letters).&lt;/p&gt;

&lt;p&gt;len(values) == 1:&lt;/p&gt;

&lt;p&gt;Constant time: O(1)&lt;/p&gt;

&lt;p&gt;🔹 Total Time Complexity: O(n)&lt;/p&gt;

&lt;p&gt;✅ Space Complexity:&lt;br&gt;
freq (Counter):&lt;/p&gt;

&lt;p&gt;Stores counts of each unique character.&lt;/p&gt;

&lt;p&gt;Space: O(k) where k is the number of unique characters.&lt;/p&gt;

&lt;p&gt;values (Set):&lt;/p&gt;

&lt;p&gt;Stores unique frequencies.&lt;/p&gt;

&lt;p&gt;Space: O(k) again.&lt;/p&gt;

&lt;p&gt;🔹 Total Space Complexity: O(k)&lt;br&gt;
Where k ≤ 26 if the input string contains only lowercase English letters.&lt;/p&gt;

&lt;p&gt;Final Answer:&lt;br&gt;
Time Complexity: O(n)&lt;/p&gt;

&lt;p&gt;Space Complexity: O(k) (usually O(1) if alphabet is fixed)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>dsa</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Longest Common Prefix When Do You Need a Zip? Let's see by solving this : Pythonic Solution</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Mon, 12 May 2025 13:57:03 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/q-do-you-need-a-zip-herelets-see-by-solving-this-longest-common-prefix-4c6b</link>
      <guid>https://forem.com/xyz_pythonic/q-do-you-need-a-zip-herelets-see-by-solving-this-longest-common-prefix-4c6b</guid>
      <description>&lt;h3&gt;
  
  
  Understanding zip(*strs) for Longest Common Prefix in Python
&lt;/h3&gt;

&lt;p&gt;Problem Statement&lt;/p&gt;

&lt;h4&gt;
  
  
  Write a function to find the longest common prefix string amongst an array of strings.
&lt;/h4&gt;

&lt;p&gt;If there is no common prefix, return an empty string "".&lt;/p&gt;

&lt;p&gt;Examples&lt;/p&gt;

&lt;p&gt;Input: strs = ["flower", "flow", "flight"]&lt;br&gt;
Output: "fl"&lt;/p&gt;

&lt;p&gt;Input: strs = ["dog", "racecar", "car"]&lt;br&gt;
Output: ""&lt;br&gt;
Explanation: There is no common prefix among the input strings.&lt;br&gt;
Constraints&lt;br&gt;
1 &amp;lt;= strs.length &amp;lt;= 200&lt;/p&gt;

&lt;p&gt;0 &amp;lt;= strs[i].length &amp;lt;= 200&lt;/p&gt;

&lt;p&gt;strs[i] consists of only lowercase English letters if non-empty&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution:
    def longestCommonPrefix(self, strs: List[str]) -&amp;gt; str:
        prefix = ""
        for chars in zip(*strs):
            if len(set(chars)) == 1:
                prefix += chars[0]
            else:
                break
        return prefix
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  How It Works
&lt;/h4&gt;

&lt;p&gt;zip(*strs)&lt;br&gt;
Transposes the list of strings by grouping characters from the same index in each string.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;strs = ["flower", "flow", "flight"]&lt;br&gt;
list(zip(*strs))&lt;br&gt;
Output: [('f','f','f'), ('l','l','l'), ('o','o','i'), ...]&lt;/p&gt;

&lt;p&gt;set(chars)&lt;br&gt;
Used to check if all characters in the same position across the strings are the same.&lt;/p&gt;

&lt;p&gt;If all match, the character is added to the prefix.&lt;/p&gt;

&lt;p&gt;If not, the loop breaks.&lt;/p&gt;

&lt;p&gt;Step-by-step Example&lt;br&gt;
Given:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;strs = ["cat", "car", "cap"]&lt;br&gt;
Position    Word 1  Word 2  Word 3&lt;br&gt;
0           c   c   c&lt;br&gt;
1           a   a   a&lt;br&gt;
2           t   r   p&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Transposed with zip(*strs):&lt;/p&gt;

&lt;p&gt;[('c', 'c', 'c'), ('a', 'a', 'a'), ('t', 'r', 'p')]&lt;br&gt;
We loop through these tuples and compare:&lt;/p&gt;

&lt;p&gt;('c', 'c', 'c') → all same → add 'c'&lt;/p&gt;

&lt;p&gt;('a', 'a', 'a') → all same → add 'a'&lt;/p&gt;

&lt;p&gt;('t', 'r', 'p') → not all same → stop&lt;/p&gt;

&lt;p&gt;Final prefix: "ca"&lt;/p&gt;

&lt;h4&gt;
  
  
  What is zip() in Python?
&lt;/h4&gt;

&lt;p&gt;The zip() function combines elements from multiple iterables (lists, tuples, etc.) by index.&lt;/p&gt;

&lt;h4&gt;
  
  
  Basic Example
&lt;/h4&gt;

&lt;p&gt;names = ["Alice", "Bob", "Charlie"]&lt;br&gt;
ages = [25, 30, 35]&lt;/p&gt;

&lt;p&gt;for pair in zip(names, ages):&lt;br&gt;
    print(pair)&lt;/p&gt;

&lt;p&gt;Output:&lt;br&gt;
('Alice', 25)&lt;br&gt;
('Bob', 30)&lt;br&gt;
('Charlie', 35)&lt;br&gt;
What does zip(*strs) do?&lt;br&gt;
It transposes the input, grouping characters by their positions.&lt;/p&gt;

&lt;p&gt;strs = ["dog", "doll", "door"]&lt;br&gt;
list(zip(*strs))&lt;br&gt;
Output: [('d', 'd', 'd'), ('o', 'o', 'o'), ('g', 'l', 'o')]&lt;br&gt;
This allows column-wise comparison of characters.&lt;/p&gt;

&lt;h4&gt;
  
  
  Why Use zip(*strs)?
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Clean and concise&lt;/li&gt;
&lt;li&gt;Automatically stops at the shortest string&lt;/li&gt;
&lt;li&gt;Easier than looping with indices&lt;/li&gt;
&lt;li&gt;Ideal for comparing strings character by character&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Use Cases for zip()
&lt;/h4&gt;

&lt;p&gt;Processing multiple sequences in parallel&lt;/p&gt;

&lt;p&gt;`students = ['Alice', 'Bob']&lt;br&gt;
scores = [90, 95]&lt;/p&gt;

&lt;p&gt;for name, score in zip(students, scores):&lt;br&gt;
    print(name, score)&lt;br&gt;
`&lt;br&gt;
Transpose a matrix&lt;/p&gt;

&lt;p&gt;matrix = [&lt;br&gt;
    [1, 2, 3],&lt;br&gt;
    [4, 5, 6]&lt;br&gt;
]&lt;/p&gt;

&lt;p&gt;transposed = list(zip(*matrix))&lt;br&gt;
Output: [(1, 4), (2, 5), (3, 6)]&lt;/p&gt;

&lt;p&gt;Compare strings by character positions&lt;/p&gt;

&lt;p&gt;words = ["flow", "flower", "flight"]&lt;/p&gt;

&lt;p&gt;for letters in zip(*words):&lt;br&gt;
    print(letters)&lt;br&gt;
When Not to Use zip()&lt;br&gt;
When working with a single list&lt;/p&gt;

&lt;p&gt;When lists are of unequal length and you need the remaining elements&lt;/p&gt;

&lt;p&gt;When element position doesn’t matter&lt;/p&gt;

&lt;p&gt;Practice Scenarios&lt;br&gt;
Scenario 1: Combine three lists into tuples&lt;/p&gt;

&lt;p&gt;a = [1, 2]&lt;br&gt;
b = ['x', 'y']&lt;br&gt;
c = ['apple', 'banana']&lt;br&gt;
list(zip(a, b, c))&lt;br&gt;&lt;br&gt;
Output: [(1, 'x', 'apple'), (2, 'y', 'banana')]&lt;br&gt;
Scenario 2: Check if two lists differ element-wise&lt;/p&gt;

&lt;p&gt;`a = [10, 20, 30]&lt;br&gt;
b = [10, 25, 30]&lt;/p&gt;

&lt;p&gt;for x, y in zip(a, b):&lt;br&gt;
    if x != y:&lt;br&gt;
        print(f"Mismatch: {x} ≠ {y}")`&lt;/p&gt;

&lt;p&gt;Scenario 3: Longest Common Prefix (Interview Example)&lt;/p&gt;

&lt;p&gt;products = ["macbook", "macpro", "macmini", "imac"]&lt;/p&gt;

&lt;p&gt;prefix = ""&lt;br&gt;
for chars in zip(*products):&lt;br&gt;
    if len(set(chars)) == 1:&lt;br&gt;
        prefix += chars[0]&lt;br&gt;
    else:&lt;br&gt;
        break&lt;/p&gt;

&lt;p&gt;print(prefix)  # Output: "mac"&lt;br&gt;
Time and Space Complexity&lt;br&gt;
Time Complexity: O(S) where S is the sum of all characters across all strings.&lt;/p&gt;

&lt;p&gt;Space Complexity: O(1) (excluding the result), since we only use a few extra variables.&lt;/p&gt;

&lt;p&gt;Summary&lt;br&gt;
Use zip(*strs) to align strings character-wise.&lt;/p&gt;

&lt;p&gt;It’s one of the most Pythonic ways to solve the longest common prefix problem.&lt;/p&gt;

&lt;p&gt;Helps simplify logic, reduce index errors, and improve readability.&lt;/p&gt;

</description>
      <category>python</category>
      <category>leetcode</category>
      <category>dsa</category>
    </item>
    <item>
      <title>2299. Strong Password Checker II</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Sun, 12 Jun 2022 03:53:34 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/2299-strong-password-checker-ii-h23</link>
      <guid>https://forem.com/xyz_pythonic/2299-strong-password-checker-ii-h23</guid>
      <description>&lt;p&gt;A password is said to be strong if it satisfies all the following criteria:&lt;/p&gt;

&lt;p&gt;It has at least 8 characters.&lt;br&gt;
It contains at least one lowercase letter.&lt;br&gt;
It contains at least one uppercase letter.&lt;br&gt;
It contains at least one digit.&lt;br&gt;
It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&amp;amp;*()-+".&lt;br&gt;
It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not).&lt;br&gt;
Given a string password, return true if it is a strong password. Otherwise, return false&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution {
public:
    bool strongPasswordCheckerII(string &amp;amp;p) {
        if(p.size()&amp;lt;8) return false;
        bool low =false, upper = false,digit = false,special =false;
        for(auto it:p){
            if(it&amp;gt;='a' and it&amp;lt;='z')low = true;
        else if(it&amp;gt;='A' and it&amp;lt;='Z')upper = true;
        else if(isdigit(it)) digit = true;
            else special = true;

        }
        //check the 6th condition 
        for(int i=0;i+i&amp;lt;p.size();i++) if(p[i] == p[i+1]) return false;
        if(low and upper and special and digit) return true;
        return false;

    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>algorithms</category>
      <category>leetcode</category>
      <category>programming</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Iterative Inorder Traversal - Leetcode</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Mon, 06 Jun 2022 09:11:09 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/iterative-inorder-traversal-leetcode-1756</link>
      <guid>https://forem.com/xyz_pythonic/iterative-inorder-traversal-leetcode-1756</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution {
public:
    vector&amp;lt;int&amp;gt; inorderTraversal(TreeNode* root) {
        //first, we create a stack 
        stack&amp;lt;TreeNode*&amp;gt;st;
        //create a node and assign it to root 
        TreeNode*node = root;
        //declare a vector which stores inorder 
        vector&amp;lt;int&amp;gt;inorder;
        while(true){
        //if the node that is the root is not null, we take that and insert it into stack
            if(node != NULL){
                st.push(node);
        //after pushing into stack, move to the left 
                node = node-&amp;gt;left;
            }
            else{
            //if you traverse a tree and end up getting null, this is what you need to do 
            //if stack is empty there are no nodes to travel
                if(st.empty() == true) break;
            //else if the st is not empty, whatever is at the top we will take it 
                node = st.top();
                st.pop();
            //and this is eventually inorder
                inorder.push_back(node-&amp;gt;val);
                node = node-&amp;gt;right;
            }

        }
        return inorder;
    }
};

//TC :O(n) , as we traverse every node 
// SC :O(h) , height of the binary tree, in worst case it is skewed tree
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Iterative Preorder Traversal</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Mon, 06 Jun 2022 08:26:41 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/iterative-preorder-traversal-19d8</link>
      <guid>https://forem.com/xyz_pythonic/iterative-preorder-traversal-19d8</guid>
      <description>&lt;p&gt;We need to use a stack for a iterative traversal and traverse from right to left , as stack follows ( Last In First Out) &lt;/p&gt;

&lt;p&gt;Below is the implementation of the code:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class Solution {
public:
    vector&amp;lt;int&amp;gt; preorderTraversal(TreeNode* root) {
        //we need to declare a vector 
     vector&amp;lt;int&amp;gt; preorder;
        //if the tree is empty , you return empty preorder 
        if(root == NULL) return preorder;


        //you then initialize the stack 
        stack&amp;lt;TreeNode*&amp;gt;st;
        st.push(root);

        //you keep iterating on the stack till it is non-empty 
        while(!st.empty()){
        //now you get the top most element 
            root = st.top();
            st.pop();
            preorder.push_back(root-&amp;gt;val);
        //check if it has a right or left on it and put it into the stack 
            if(root-&amp;gt;right!=NULL){
                st.push(root-&amp;gt;right);
            }
             if(root-&amp;gt;left!=NULL){
                st.push(root-&amp;gt;left);
            }


        }

        return preorder;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Time Complexity  :O(n) , because we are travelling every node &lt;br&gt;
Space Complexity :O(n) , ( this is the worst case in case of &lt;br&gt;
                  skewed tree) &lt;/p&gt;

</description>
    </item>
    <item>
      <title>160. Intersection of Two Linked Lists - Leetcode</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Mon, 06 Jun 2022 07:35:48 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/160-intersection-of-two-linked-lists-leetcode-3f3d</link>
      <guid>https://forem.com/xyz_pythonic/160-intersection-of-two-linked-lists-leetcode-3f3d</guid>
      <description>&lt;h4&gt;
  
  
  Naive Approach :
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Find the length of both the lists &lt;/li&gt;
&lt;li&gt;Find the difference in the length of both the lists &lt;/li&gt;
&lt;li&gt;Then start checking the equality for the nodes &lt;/li&gt;
&lt;li&gt;Once we find equal node return that node &lt;/li&gt;
&lt;li&gt;otherwise if we reach at the end return the null&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  There is a better way to do it:
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;We are going to traverse the shorter one and longer one at the same time&lt;/li&gt;
&lt;li&gt;We are going to set pointers to the heads of both of these.&lt;/li&gt;
&lt;li&gt;When we get at the end of the shorter one, we set the pointer to the head of the longer one.&lt;/li&gt;
&lt;li&gt;When we get at the end of the longer one, we set the pointer to the head of the shorter one.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Here, is the code of the implementation
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

        if(headA == NULL|| headB == NULL) return NULL;
        ListNode*a_pointer = headA;
        ListNode*b_pointer = headB;

        //while the nodes are not equal 
        while(a_pointer != b_pointer ){
            if(a_pointer == NULL){
              //this means it is at the end of the list 
                a_pointer = headB;   
            } 

        else{
            a_pointer = a_pointer-&amp;gt;next;
        }

              if(b_pointer == NULL){
               //this means it is at the end of the list 
                b_pointer = headA;   
              } 

        else{
            b_pointer = b_pointer-&amp;gt;next;
        }
        }
        return a_pointer;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>algorithms</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Sum Tree</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Sat, 04 Jun 2022 10:07:19 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/sum-tree-43p9</link>
      <guid>https://forem.com/xyz_pythonic/sum-tree-43p9</guid>
      <description>&lt;p&gt;This post discusses the solution of the problem - &lt;a href="https://practice.geeksforgeeks.org/problems/sum-tree/1" rel="noopener noreferrer"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We need to solve this problem using Children Sum Property, which means sum of left and right child should be equal to its root. A tree with single node, is also considered to be following children sum property.A empty tree is also considered to be following Children Sum Property.&lt;/p&gt;

&lt;p&gt;Below is the solution of the problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution
{
    public:

    int findSum(Node*root){
        if(!root) return 0;
        return root-&amp;gt;data +findSum(root-&amp;gt;left)+findSum(root-&amp;gt;right);
    }
    bool isSumTree(Node* root)
    {
         // Your code here
         if(!root) return true;
         if(!root-&amp;gt;left &amp;amp;&amp;amp; !root-&amp;gt;right) return true;

         if(findSum(root-&amp;gt;left)+findSum(root-&amp;gt;right) == root-&amp;gt;data)
         return (isSumTree(root-&amp;gt;left) &amp;amp;&amp;amp; isSumTree(root-&amp;gt;right));
         else return false;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>dsa</category>
      <category>algorithms</category>
      <category>trees</category>
      <category>gfg</category>
    </item>
    <item>
      <title>Construct a Binary Tree from Inorder and Postorder</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Sat, 04 Jun 2022 09:50:04 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/construct-a-binary-tree-from-inorder-and-postorder-a7b</link>
      <guid>https://forem.com/xyz_pythonic/construct-a-binary-tree-from-inorder-and-postorder-a7b</guid>
      <description>&lt;p&gt;When we are given a root,left and right subtree : &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inorder&lt;/strong&gt;  :  Left Root Right &lt;br&gt;
&lt;strong&gt;Preorder&lt;/strong&gt; :  Root Left Right&lt;/p&gt;

&lt;p&gt;We can get the root from the Preorder traversal, and the first element from the Preorder traversal is Root.If we locate the root, we can find the left and right side of the tree easily. We can follow the similar fashion and construct the whole tree.&lt;/p&gt;

&lt;p&gt;Here is the code of the solution&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Solution{
    public:
    int order=0;
    Node* build(int in[],int pre[],int s,int e){
        if(s&amp;gt;e){
            return NULL;
        }
        Node* root=new Node(pre[order++]);
        int index=0;
        for(int i=s;i&amp;lt;=e;i++){
            if(in[i]==root-&amp;gt;data){
                index=i;
                break;
            }
        }
        root-&amp;gt;left=build(in,pre,s,index-1);
        root-&amp;gt;right=build(in,pre,index+1,e);
        return root;
    }
    Node* buildTree(int in[],int pre[], int n)
    {
        return build(in,pre,0,n-1);
        // Code here
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Maximum Subarray - Leetcode Solution</title>
      <dc:creator>pythonic_solutions</dc:creator>
      <pubDate>Tue, 22 Feb 2022 16:43:11 +0000</pubDate>
      <link>https://forem.com/xyz_pythonic/maximum-subarray-leetcode-solution-60f</link>
      <guid>https://forem.com/xyz_pythonic/maximum-subarray-leetcode-solution-60f</guid>
      <description>&lt;p&gt;Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.&lt;/p&gt;

&lt;p&gt;A subarray is a contiguous part of an array.&lt;/p&gt;

&lt;p&gt;We need to use Kadane's Algorithm here&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Kadane's Algorithm

class Solution {
public:
    int maxSubArray(vector&amp;lt;int&amp;gt;&amp;amp; nums) {
        int ans =INT_MIN,sum =0;
        int n=nums.size();
        for(int i=0;i&amp;lt;n;++i){
           sum+=nums[i];
           ans = max(ans,sum);
        if(sum&amp;lt;0)
            sum=0;

        }
        return ans;

        }      

};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>cpp</category>
      <category>leetcode</category>
    </item>
  </channel>
</rss>
