<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohima Chaudhuri on Medium]]></title>
        <description><![CDATA[Stories by Mohima Chaudhuri on Medium]]></description>
        <link>https://medium.com/@emailmohimac?source=rss-5d8a972c8a56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QjmIfgHixIZU9wuVEaCXKA.jpeg</url>
            <title>Stories by Mohima Chaudhuri on Medium</title>
            <link>https://medium.com/@emailmohimac?source=rss-5d8a972c8a56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:37:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emailmohimac/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Two Pointer problems]]></title>
            <link>https://levelup.gitconnected.com/two-pointer-problems-734c96b6dee8?source=rss-5d8a972c8a56------2</link>
            <guid isPermaLink="false">https://medium.com/p/734c96b6dee8</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Mohima Chaudhuri]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 00:25:54 GMT</pubDate>
            <atom:updated>2025-04-11T00:25:54.862Z</atom:updated>
            <content:encoded><![CDATA[<p>The two-pointer technique is a versatile algorithmic approach used to solve problems involving arrays, lists, or strings by maintaining two pointers that move through the data structure in a coordinated manner. The primary goal of this technique is to improve either the space or the time efficiency of a solution compared to more naive or brute-force methods.<br>How we move the pointers depends on the type of problem to solve.</p><h4><a href="https://leetcode.com/problems/valid-palindrome">Valid Palindrome</a></h4><p><strong>Input:</strong> We are given a string that may contain non-alphanumeric characters and mixed-case. The string is considered a palindrome if, after ignoring non-alphanumeric characters, it reads the same forwards and backwards.</p><p>Example:</p><p>RACE — car!! : palindrome</p><p>bb**88 : palindrome</p><p>racer--car : not a palindrome</p><p><strong>Naive Approach:</strong></p><ol><li>First, transform the string by removing non-alphanumeric characters and converting characters to lower-case for uniformity</li><li>Then, compare the transformed string with its reverse.</li></ol><pre>class Solution:<br>    def isPalindrome(self, s: str) -&gt; bool:<br>        def transform_str(s):<br>            res = &#39;&#39;          # extra space for the transoformed string<br>            for c in s:<br>                if c.isalnum():<br>                    res += c.lower()<br>            return res<br>        s = transform_str(s)<br>        if s == s[::-1]:      # extra space for the reversed string<br>            return True<br>        return False</pre><p><strong>Optimized Approach:</strong><br> Instead of creating a new transformed string, we use two pointers — one starting from the left and the other from the right. The process is as follows:</p><ol><li>Check if the characters at both pointers are alphanumeric.</li><li>If either character is not alphanumeric, move the corresponding pointer inward without any comparison.</li><li>Once both pointers point to alphanumeric characters, compare them.</li><li>If the characters are equal, continue moving both pointers inward. If they differ, the string is not a palindrome.</li></ol><p>This approach performs all the operations in-place without requiring extra space.</p><p><strong>Time Complexity:</strong> O(n)<br> <strong>Space Complexity:</strong> O(1)</p><p><strong>Comparison of Naive vs Optimized Approaches:</strong></p><ul><li>The naive approach requires O(n) space due to the need to store the transformed string and its reverse.</li><li>The optimized approach, however, operates in constant space (O(1)) while maintaining linear time complexity (O(n)).</li></ul><pre>class Solution:<br>    def isPalindrome(self, s: str) -&gt; bool:<br><br>        start, end = 0, len(s)-1<br>        if not s:<br>            return True<br>        while start &lt; end:<br>            if not s[start].isalnum():<br>                start += 1<br>                continue<br>            if not s[end].isalnum():<br>                end -= 1<br>                continue<br>            if s[start].lower() != s[end].lower():<br>                return False<br>            start += 1<br>            end -= 1<br>        return True</pre><h4><a href="https://leetcode.com/problems/is-subsequence/">Is subsequence</a></h4><p><strong>Input: </strong>We are given two character arrays: a <strong>source</strong> array and a <strong>target</strong> array. Our task is to determine whether the characters of the <strong>source</strong> array appear in the <strong>target</strong> array in the same order.</p><p><strong>Example:</strong></p><p>src: ‘abc’. target: ‘<strong>a</strong>d<strong>b</strong>e<strong>c</strong>f’ : since source characters exists in target and order of characters is same so this returns True</p><p>src: ‘abc’ target: ‘<strong>a</strong>d<strong>c</strong>e<strong>b</strong>f’: here source characters are present in the target but not in the correct order and should return False</p><p><strong>Approach:</strong></p><p>We use two pointers: p_source and p_tgt, which start at the beginning of the <strong>source</strong> and <strong>target</strong> arrays, respectively. We then compare the characters at these pointers:</p><ul><li>If they match, we move both pointers forward by 1.</li><li>If they don’t match, we only move p_tgt forward, since we haven&#39;t found a match for the current character in the <strong>source</strong> array.</li></ul><p>After the loop, if p_source hasn&#39;t reached the end of the <strong>source</strong> array, it means one or more characters haven&#39;t found a match in the <strong>target</strong> array, so we return False. Otherwise, we return True.</p><pre>class Solution:<br>    def isSubsequence(self, s: str, t: str) -&gt; bool:<br>        s_ptr, t_ptr = 0,0<br>        while s_ptr in range(len(s)) and t_ptr in range(len(t)):<br>            if s[s_ptr] == t[t_ptr]:<br>                s_ptr += 1<br>                t_ptr += 1<br>            else:<br>                t_ptr += 1<br>        if s_ptr &lt; len(s):<br>            return False<br>        return True</pre><h4><a href="https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/?envType=study-plan-v2&amp;envId=top-interview-150">Two sum ii (sorted input)</a></h4><p><strong>Input:</strong><br> We are given a sorted array and a target sum. The task is to determine if any two values in the array sum up to the target.</p><p>Example:</p><pre>Input: numbers = [2,7,11,15], target = 9<br>Output: [0,1]<br>Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 0, index2 = 1.<br>We return [0,1].</pre><p><strong>Approach:</strong><br> Leverage the fact that the array is sorted by using two pointers — one starting from the beginning (low) and the other from the end (high) of the array. The process works as follows:</p><ol><li>Compute the sum of the values at the two pointers.</li><li>If the sum equals the target, we’ve found the solution.</li><li>If the sum is greater than the target, we need a smaller sum, so we move the high pointer one step left (decrement it).</li><li>If the sum is less than the target, we need a larger sum, so we move the low pointer one step right (increment it).</li></ol><p>Repeat the process until the two pointers meet or a solution is found.</p><pre>class Solution:<br>    def twoSum(self, numbers: List[int], target: int) -&gt; List[int]:<br>        low = 0<br>        high = len(numbers) - 1<br>        while low &lt; high:<br>            sum = numbers[low] + numbers[high]<br><br>            if sum == target:<br>                return [low, high]<br>            elif sum &lt; target:<br>                low += 1<br>            else:<br>                high -= 1<br>        # In case there is no solution, return [-1, -1].<br>        return [-1, -1]</pre><h4><a href="https://leetcode.com/problems/container-with-most-water/description/?envType=study-plan-v2&amp;envId=top-interview-150">Container with most water</a></h4><p><strong>Input</strong></p><p>An array of integers where each element represents the height of a vertical line.<br> Each pair of lines, with the x-axis, forms a container.<br> <strong>Goal:</strong> Find the maximum amount of water that can be trapped between any two lines.</p><pre>Input: height = [1,8,6,2,5,4,8,3,7]<br>Output: 49<br>Explanation: In this case, the max area of water the container can contain <br>is 49.</pre><p>To calculate how much water can be held between two vertical lines:</p><ul><li>Let’s say the lines are at index i and index j in the array (with i &lt; j).</li><li>The <strong>width</strong> of the container is the distance between these two indices:<br> width = j - i</li><li>The <strong>height</strong> of the container is limited by the shorter line:<br> height = min(height[i], height[j])</li><li>So, the <strong>area (water volume)</strong> is:<br> area = width × height = (j - i) × min(height[i], height[j])</li></ul><p><strong>Approach:</strong></p><p><strong>Brute Force</strong></p><ul><li>Check all pairs of lines.</li><li>Compute the area for each.</li><li>Track the max area</li></ul><p>🕒 <strong>Time:</strong> O(n²)<br> 🧠 <strong>Space:</strong> O(1)</p><p><strong>Optimized (Two-Pointer Technique)</strong></p><ol><li>Start with two pointers: one at the beginning, another at the end.</li><li>Compute the area between them.</li><li>Move the pointer pointing to the <strong>shorter</strong> line inward.</li><li>Repeat until pointers meet.</li></ol><p>🔍 <strong>Why move the shorter line?</strong><br> Because height is limited by the shorter line — to potentially find a taller one, we must move it.</p><p>Why do we not move the index of the taller line?<br>Because even if we find a higher value it cannot impact the overall area as the area is constrained by the minimum value between 2 heights</p><p>🕒 <strong>Time:</strong> O(n)<br> 🧠 <strong>Space:</strong> O(1)</p><h3>3-sum</h3><p><strong>Input:</strong></p><p>Given an integer array, find all unique triplets such that the sum of the three numbers is zero. Duplicate triplets should be excluded from the result.</p><p>Example:</p><pre>Input: nums = [-1,0,1,2,-1,-4]<br>Output: [[-1,-1,2],[-1,0,1]]</pre><p><strong>Approach:</strong></p><p>This is an extension of the two-sum problem, optimized using sorting and a two-pointer technique.</p><ol><li><strong>Sort the array</strong> to make it easier to handle duplicates and apply the two-pointer approach.</li><li>Iterate through the array, treating each element as a <strong>pivot</strong>.</li><li>For each pivot, use the two-pointer method to find a pair of numbers (to the right of the pivot) that, together with the pivot, sum to zero.</li></ol><h4>Edge Cases and Optimizations:</h4><ol><li><strong>Break early:</strong><br> If the pivot element is greater than zero, break out of the loop. Since the array is sorted, all remaining numbers will also be greater than zero, and no triplet can sum to zero.</li><li><strong>Skip Duplicate Pivots:</strong><br> If the current pivot is the same as the previous one, skip it to avoid duplicate triplets.</li><li><strong>Avoid Duplicate Pairs in Two-Pointer Search:</strong><br> When scanning for pairs with the two-pointer technique, skip over duplicate values to ensure all triplets are unique.</li></ol><pre>class Solution:<br>    def threeSum(self, nums: List[int]) -&gt; List[List[int]]:<br>        nums.sort()<br>        result = []<br>        i = 0<br>        for i in range(len(nums)-2):<br>            if nums[i] &gt; 0:<br>                break<br>            if i != 0 and nums[i]==nums[i-1]:<br>                continue<br>            self.twosum(nums, result, i)<br>            <br>        return result<br>    def twosum(self, nums, result, i):<br>        lo=i+1<br>        hi = len(nums)-1<br>        tgt = 0-nums[i]<br>        while lo&lt;hi:<br>            if nums[hi]+nums[lo]==tgt:<br>                result.append([nums[i],nums[lo], nums[hi]])<br>                lo, hi = lo+1, hi-1<br>            elif nums[hi]+nums[lo] &gt; tgt:<br>                hi -= 1<br>            else:<br>                lo += 1<br>            while lo&lt;hi and nums[lo]==nums[lo-1]:<br>                lo += 1<br>        </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734c96b6dee8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/two-pointer-problems-734c96b6dee8">Two Pointer problems</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O Notation]]></title>
            <link>https://levelup.gitconnected.com/big-o-notation-cc84d39220ed?source=rss-5d8a972c8a56------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc84d39220ed</guid>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Mohima Chaudhuri]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 14:20:44 GMT</pubDate>
            <atom:updated>2025-03-17T14:20:44.503Z</atom:updated>
            <content:encoded><![CDATA[<p>In computer science Big O refers to the growth rate of a program’s runtime or space as the input size increases(towards infinity), ie: how the runtime of a program behaves as the input size increases. It is an a<strong>symptotic upper bound</strong> on the growth rate of an algorithm’s runtime or space usage as the input size n increases. (From Wikipedia)</p><p>Let’s break it down.</p><p>What does asymptotic mean?<br>A<strong>symptotic</strong> describes the behaviour of a function as its argument (often representing input size) approaches <strong>infinity. </strong>It’s about understanding the <strong><em>trend of the functio</em>n</strong> rather than its precise values, especially when the input size becomes very large.</p><p>Big O notation in computer science is fundamentally used to <strong>classify algorithms based on how their runtime or space requirements scale as the input size increases</strong></p><p>To simplify Big O defines runtime as a function of the input size of a program.</p><h3><strong>How to evaluate</strong></h3><ul><li><strong>Worst-Case Analysis:</strong> Big O notation in computer science describes the <strong>worst-case scenario</strong>. This analysis considers the <em>upper bound</em> on the algorithm’s performance as <em>the input size becomes arbitrarily large,</em> providing a guarantee on the maximum resources the algorithm might require. Always good to know how bad can it get when things scale, right?</li><li><strong>Dominant Terms:</strong> As the input size $n$ grows towards infinity, the <strong>term with the highest growth rate in the function will eventually dominate</strong> the overall runtime or space usage1 …. Lower-order terms and constant factors become insignificant in comparison.</li></ul><h3><strong>Types of Big O notation commonly encountered</strong></h3><p>Let’s go over this with the example of an ice cream shop.</p><p>We have a list of ice cream flavours and another list with ice cream containers.</p><h4>O(1): Get the first ice cream flavour from the list.</h4><p>This will always have a constant run time. No matter how big the list grows it will always take the same time to get the first item. This applies to any item since array lookups are always constant time. This means that the input size has no impact on the run time.</p><pre># Lists of ice cream flavors and containers<br>icecream_flavors = [&#39;vanilla&#39;, &#39;chocolate&#39;, &#39;biscoff&#39;]<br>icecream_containers = [&#39;cone&#39;, &#39;cup&#39;, &#39;waffle-cone&#39;, &#39;stick&#39;]<br><br># Step 1: Generate the first combination directly (O(1) time complexity)<br>first_ice_cream = [icecream_flavors[0], icecream_containers[0]]<br><br># Print the first ice cream combination<br>print(&quot;The first ice cream combination is:&quot;, first_ice_cream)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lewuO65zPoh7jUd6tfTR4Q.png" /></figure><h4>O(N): check inventory</h4><p>Let’s say we get an input as a flavour and need to check if we have that in our shop. In that case we search through all the ice cream flavors to check if we have it. We are doing a linear search here. Note that it is possible that the first item itself is what we are looking for but we will always evaluate the worst case, hence the run time is O(N) meaning the item searched could be at the end of the list or not in the list at all.</p><pre># List of available ice cream flavors<br>ice_cream_flavors = [&#39;vanilla&#39;, &#39;chocolate&#39;, &#39;biscoff&#39;, &#39;mint&#39;, &#39;strawberry&#39;]<br><br># Function to check if a flavor is in stock<br>def check_flavor_in_stock(flavor, flavors_list):<br>    # Time complexity: O(n), because we are searching the list one element at a time<br>    if flavor in flavors_list:<br>        return True  # Flavor is in stock<br>    else:<br>        return False  # Flavor is not in stock</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovLBs2Tp4H2XLZVziktNmg.png" /></figure><h4>O(n²): Nested loops</h4><p>Example make a combination of every flavor and container type, where number of flavors = number of container types</p><pre># List of ice cream flavors<br>ice_cream_flavors = [&#39;vanilla&#39;, &#39;chocolate&#39;, &#39;biscoff&#39;]<br><br># List of ice cream container types<br>ice_cream_containers = [&#39;cone&#39;, &#39;cup&#39;, &#39;waffle-cone&#39;]<br><br># Nested loop to generate combinations<br>for flavor in ice_cream_flavors:  # Outer loop O(n)<br>    for container in ice_cream_containers:  # Inner loop O(n)<br>        print(f&quot;{flavor} in a {container}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PMdrDXpfbd03WF_HEH-7A.png" /></figure><p><em>Note: For the above example if the list of flavors and list of containers are of varying lengths then the runtime would be O(m*n) instead of O(n*n). This takes into factor multiple variables when calculating the Big O runtime.</em></p><h4>O(logN): input reduces by half at each step</h4><p>Say we sort the list of our ice cream flavors and then do a binary search through it. This would reduce our search space by half at every repetition.</p><p>1st iteration -&gt; n/2</p><p>2nd iteration -&gt; n/4</p><p>3rd iteration: n/8</p><p>kth iteration -&gt; n/2^k</p><p>n ~ 2^k</p><p>k ~ log(n)</p><pre># Time Complexity: O(log n) for binary search<br>def binary_search(arr, target):<br>    &quot;&quot;&quot;<br>    Perform binary search on a sorted list of ice cream flavors to find the target flavor.<br>    <br>    :param arr: Sorted list of ice cream flavors<br>    :param target: The flavor to search for<br>    :return: Index of the target flavor if found, else -1<br>    &quot;&quot;&quot;<br>    low = 0<br>    high = len(arr) - 1<br>    <br>    while low &lt;= high:<br>        mid = (low + high) // 2<br>        guess = arr[mid]<br>        <br>        # If target is found, return the index<br>        if guess == target:<br>            return mid<br>        # If target is less than the mid value, discard the right half<br>        elif guess &gt; target:<br>            high = mid - 1<br>        # If target is greater than the mid value, discard the left half<br>        else:<br>            low = mid + 1<br>            <br>    # If the target is not found<br>    return -1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWo4RzQl1oUPADQVpmGHaQ.png" /></figure><h4><strong>Omitting constants and lower order terms:</strong></h4><pre># List of ice cream flavors<br>ice_cream_flavors = [&#39;vanilla&#39;, &#39;chocolate&#39;, &#39;biscoff&#39;, &#39;mint&#39;, &#39;strawberry&#39;]<br><br># List of ice cream container types<br>ice_cream_containers = [&#39;cone&#39;, &#39;cup&#39;, &#39;waffle-cone&#39;, &#39;stick&#39;]<br><br># Step 1: Nested loops (O(n^2) time complexity)<br>for flavor in ice_cream_flavors:  # Outer loop O(n)<br>    for container in ice_cream_containers:  # Inner loop O(n)<br>        print(f&quot;{flavor} in a {container}&quot;)  <br><br># Step 2: Additional operation (O(n) time complexity)<br>for flavor in ice_cream_flavors:  # This loop adds O(n)<br>    print(f&quot;Checking stock for {flavor}&quot;)  # A linear operation (O(1) inside)<br><br># Step 3: Constant time operation (O(1) time complexity)<br>print(&quot;End of the order&quot;)  # O(1) operation</pre><p>The overall runtime for the above program can be denoted by:</p><p>O(n²) + O(n) + O(1)</p><p>Let’s see how this behaves as n increases:<br>O(3²)+O(3)+O(1) = 9+3+1 = 13operations</p><p>O(10²)+O(10)+O(1)= 100+10+1 = 111operations</p><p>O(100²)+O(100)+O(1) = 10,000+100+1 = 10,101operations</p><ul><li>For <strong>small </strong><strong>n (e.g., 3)</strong>, all the terms <strong>O(n² + n + 1)</strong> contribute significantly to the total runtime. However, as n increases, the <strong>O(n²)</strong> term grows much faster than the other two terms.</li><li>For <strong>large </strong><strong>n (e.g., 1000)</strong>, the <strong>O(n²)</strong> term becomes dominant, and the contributions from <strong>O(n)</strong> and <strong>O(1)</strong> become negligible.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc84d39220ed" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/big-o-notation-cc84d39220ed">Big O Notation</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Automation? It’s Easy If You Get the Basics]]></title>
            <link>https://levelup.gitconnected.com/web-automation-its-easy-if-you-get-the-basics-e35227247162?source=rss-5d8a972c8a56------2</link>
            <guid isPermaLink="false">https://medium.com/p/e35227247162</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mohima Chaudhuri]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 21:32:58 GMT</pubDate>
            <atom:updated>2020-04-05T21:32:58.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EVpIdAzJ34ljpfZe" /><figcaption>Photo by <a href="https://unsplash.com/@roadtripwithraj?utm_source=medium&amp;utm_medium=referral">Road Trip with Raj</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will try to understand the building blocks for web automation. Let’s start with a broad category of things to know to get started:</p><ol><li>Any programming language that is supported by Selenium, in my case it is Python.</li><li>The selenium web driver API — which is pretty well documented. Like any library, we search for things that we need from here and use them.</li><li>Framework development — this includes structuring tests, abstraction to simplify writing test scripts, detect and run tests, reporting results, etc.</li></ol><p>In this article, we will get into the details of #2 the selenium web driver API.</p><h4>Architecture of WebDriver</h4><p>The selenium web driver is basically an API that talks to browser-specific drivers. These drivers actually send commands to the respective browsers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxKMQNTZvZx7oy5q5rAaVg.png" /></figure><h4>Installation</h4><p>I have mentioned the versions used for my setup, but any compatible versions can be used.</p><ol><li>Install Python (version 3.7)</li></ol><p>Download and run the installer from <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p><p>2. Install the selenium library(version 3.141.0)</p><pre>- Open Terminal<br>- Run the command : pip3 install selenium<br>- Run the command : pip3 freeze and verify that the library is installed.</pre><p>3. Install the chrome driver from <a href="https://chromedriver.chromium.org/downloads">https://chromedriver.chromium.org/downloads</a>. Make sure this matches the Chrome browser version(Version 80.0.3987.162). Add the path to the driver in the PATH environment variable.</p><p>4. Install PyCharm. This is optional at this stage since we can run all selenium commands from the IDE, required for framework development.</p><h4>Instantiate the web driver</h4><p>Every browser like Chrome/IE/Firefox has different behaviors because they are different programs with similar functionalities. Due to this, for every browser, there is a separate WebDriver class defined with distinct __init__ methods for initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bK0OnQgo3PUnCL_3nD5NKw.png" /><figcaption>webdriver.py</figcaption></figure><p>In our code when we write:</p><pre>driver = Webdriver.Chrome()</pre><p>it will actually call the __init__ method from the chrome/webdriver.py module.</p><h4>Classifying the webdriver API</h4><p>Essentially the selenium library is all about interacting with web pages and different web elements. We can broadly categorize the library into the following set of functionalities:-</p><ul><li>Navigate — go to a page, move back or forward, etc</li><li>Locate — get web elements on a page by uniquely identifying them.</li><li>Update — interact with the web elements located. Click a button, input text into a text box, select/clear a field, etc.</li><li>Synchronize — imagine trying to interact with an element on a page and it is not interactable, which can mean several things as we will see and how these interactions can be synchronized using <em>waits.</em></li></ul><h4>Navigate</h4><p>This is the simplest. Go to a page, move back, move forward, and that’s it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb75e19397d00d8c30186047a951d49/href">https://medium.com/media/bcb75e19397d00d8c30186047a951d49/href</a></iframe><h4>Locate</h4><blockquote>Before we start locating web elements we need to know — What is the DOM?</blockquote><p>HTML (HyperTextMarkupLanguage) is a markup language that expresses the content and format of a web page. The DOM (Document Object Model) is a language-independent API that treats HTML document as a tree structure where <strong>each node represents an object in the document</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*8L2KzdEknWkrlLiWQycGpg.png" /></figure><p>The DOM representation allows external programs to access and manipulate elements on a web page and this is used by the selenium webdriver to interact with the web elements.</p><p>Types of DOM elements:</p><ol><li>Document: the entire web page is a document.</li><li>Element: All tags inside an HTML -open and corresponding closing tags included.</li><li>Text: all text within a tag</li><li>Attributes: attributes for a specific HTML element. Ex: class/id, etc.</li></ol><p>There are two basic methods in Selenium to locate web elements: <em>find_element</em> and <em>find_elements</em>. Both take arguments of a locator strategy followed by the value for the locator strategy and return an object of type WebElement or a list of web elements respectively. All other methods in the form of find_element_by_* <em>actually</em> <em>call the find_element function internally. </em>If there is no match then a NoSuchElementFound exception is raised.</p><pre><strong>Tip</strong>: to look at the method definition of Selenium functions from PyCharm, point cursor at the method name and do a CTRL+click. </pre><blockquote>What is a locator strategy? It is an attribute of a web element that can be used to identify it. Example: for an employee entity, we can use the employee id as a unique identifier. In the absence of a unique identifier, we can use a combination of attributes like name and department. Similarly, web elements can have ids that are unique, in the absence of a unique identifier we can use a combination of attributes to uniquely identify a web element. These attributes can be id, class, tag name, link text, partial link text, XPath or CSS.</blockquote><h4>Locate — Example of find_element_by_* methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBsbHX3fCjBQVdm2gtMJ3A.png" /><figcaption>find_element_by_* methods</figcaption></figure><pre><strong>Note</strong>: All these methods have a corresponding <em>find_elements_by_*</em> method as well. These methods return a list of matched web elements or an empty list if no match is found.</pre><h4><strong>Locate — Choosing a locator strategy</strong></h4><ul><li>If the element has a unique attribute, use the find_element_by_* method with its corresponding attribute. Ex: if the id is a unique identifier then use the find_element_by_id method.</li><li>If there are no unique attributes then use compact CSS selectors.</li><li>Tag names will have multiple matches so it is not recommended to be used.</li><li>Searching the DOM is expensive so to reduce time, choose compact xpaths that narrow down the search scope to a great extent.</li></ul><h4><strong>Locate — Understanding the find_element method syntax</strong></h4><p>This is the signature for the find_element method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kelatWBUh62jiulUhNjMg.png" /><figcaption>find_element method signature</figcaption></figure><p>This is how we call the find_element method in scripts</p><pre>input_username = driver.find_element(By.ID, &#39;userSignInFormEmail&#39;)</pre><blockquote>What does the By.ID refer to? It is nothing but the string ‘id’. If we look at the By class we can see that it has the locator strategies as attributes of the class, so that they can be accessed easily with the class_name.attribute syntax.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3yie4uTxCrv_yghrHdEQQ.png" /><figcaption>the By class</figcaption></figure><p>We could also write the above statement as below but we use the By.attribute because that is the recommended way to do it.</p><pre>input_username = driver.find_element(id, &#39;userSignInFormEm</pre><p>Let us look briefly on how to identify elements using CSS followed by Xpaths.</p><p><strong>Locate — CSS/ Cascading Style Sheets</strong></p><p>This is a language that controls how a web page is displayed/presented. A CSS rule is a set of properties associated with a selector. Using this — different parts of the web page can be formatted in sections. Websites have several CSS rules.</p><p>Example of a CSS rule:</p><pre>/* The selector &quot;p&quot; indicates that all paragraphs in the document will be affected by that rule */<br>p {<br>  /* The &quot;color&quot; property defines the text color, in this case yellow. */<br>  color: yellow;<br><br>  /* The &quot;background-color&quot; property defines the background color, in this case black. */<br>  background-color: black<br>}</pre><p>We need to know only about the CSS selectors and not the rules.</p><p>Let&#39;s look at a sample HTML and clarify some terms before starting with CSS selectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDhoBCx50qhEn9Cjjqz2lg.png" /><figcaption>elements and attributes</figcaption></figure><h4>Locate — Example for simple CSS selectors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvLsIIBiEmZ8cNxhnSEF7g.png" /><figcaption>Simple CSS Selectors</figcaption></figure><h4>Locate — Example for selectors with attributes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piaHe0W9XaqZeSk0G2qRQw.png" /><figcaption>Selectors with attributes</figcaption></figure><h4>Locate — Example of Combinators/defining relationships between elements</h4><p>We will use the sample HTML below for this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MX1doYdZdy4d7bzPxxo2WA.png" /><figcaption>sample HTML for CSS combinators</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIn_hHvh6obxdDG8rfDKPg.png" /><figcaption>Combinator CSS selectors</figcaption></figure><h4><strong>Locate — Example of nth matches</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mp6sryZMk3h0xsfxwtuxRw.png" /><figcaption>nth match CSS selector</figcaption></figure><h4>Locate — Example of XPATH locators</h4><p>XPath/XML Path Language can be used to locate elements in a hierarchical structure like XML. Since the DOM(Document Object Model) is also hierarchical, we can use xpaths to locate web elements.</p><p>Xpaths can be absolute which means it will start at the root of the DOM or relative meaning it could start anywhere in the DOM.</p><h4><strong>Locate — Example of main components of XPath</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpeeIMZ5eanBpCLkHRZaaQ.png" /><figcaption>Xpath Components</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZwOpta_ZIRpH6pn7Va_bg.png" /><figcaption>Components of Xpath contd.</figcaption></figure><h4><strong>Locate — Example of axes/relationships in Xpath locators</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rfv2AmP7gpVf2xK1-T7l3Q.png" /><figcaption>XPath axes</figcaption></figure><h4>Update — Interacting with different elements</h4><p>Now that we know how to locate web elements, time to see how we can interact with them. A broad category of web elements includes textbox, buttons, dropdown lists, radio buttons, and scroll bars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dj_S286OAtfzEVRdbBE34A.png" /><figcaption>interact with web elements</figcaption></figure><h4>Synchronize — Waits</h4><p>Imagine talking to a person when she is not listening, no matter what was said we will not get the expected outcome because of not being heard. To solve this we need synchronization so that we talk only when the other person is listening. Similarly, if we are not careful with the automation, we might end up clicking buttons when they are not enabled or entering input into a text box that is not visible. This will cause the code to stop with exceptions. We can avoid this by using waits.</p><p>There are 2 types of waits in Selenium: implicit and explicit.</p><p>Implicit Wait is a webdriver method. This wait can be set for the entire webdriver session. It is not specific to any web element. Not recommended to use this wait for automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*ih-n2wKY7mugrr0-svyK8Q.png" /><figcaption>implicit wait</figcaption></figure><p>Explicit Waits can be customized for different web elements. The explicit wait will wait for a specified time until a condition evaluates to True(expected conditions).</p><p>To implement explicit waits there are 2 classes that should be imported apart from webdriver:WebDriverWait and expected_conditions.</p><p>First, we need to create a WebDriverWait object and initialize it. Next, call the until method of the WebdriverWait class on this object. The until method checks the condition that is passed as its argument. If the condition is True it returns corresponding return value, if it evaluates to False at the end of the wait time then it throws a TimeOutException.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqbY4BNvg-Fu70_OaR7xSQ.png" /><figcaption>Explicit wait syntax explained</figcaption></figure><p>With this, we come to the end of this article. This is not an all-encompassing list but a brief overview. To know the library better it is always recommended to read the source code and docs.</p><h4>Resources</h4><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML">https://developer.mozilla.org/en-/docs/Learn/HTML/Introduction_to_HTML</a></li><li><a href="https://www.selenium.dev/docs/site/en/">https://www.selenium.dev/docs/site/en/</a></li><li><a href="https://www.amazon.in/Learning-Selenium-Testing-Tools-Python-ebook/dp/B00RP13D10">https://www.amazon.in/Learning-Selenium-Testing-Tools-Python-ebook/dp/B00RP13D10</a></li><li><a href="http://elementalselenium.com/tips">http://elementalselenium.com/tips</a></li><li><a href="https://www.red-gate.com/simple-talk/dotnet/.net-framework/xpath,-css,-dom-and-selenium-the-rosetta-stone/">https://www.red-gate.com/simple-talk/dotnet/.net-framework/xpath,-css,-dom-and-selenium-the-rosetta-stone/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e35227247162" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/web-automation-its-easy-if-you-get-the-basics-e35227247162">Web Automation? It’s Easy If You Get the Basics</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Way For The Matrix — A Complete Guide to Solving 2D Array Coding Problems]]></title>
            <link>https://levelup.gitconnected.com/make-way-for-the-matrix-a-complete-guide-to-solving-2d-array-coding-problems-725096d122d9?source=rss-5d8a972c8a56------2</link>
            <guid isPermaLink="false">https://medium.com/p/725096d122d9</guid>
            <category><![CDATA[problems]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mohima Chaudhuri]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 03:47:44 GMT</pubDate>
            <atom:updated>2020-02-18T03:49:42.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>Make Way For The Matrix — A Complete Guide to Solving 2D Array Coding Problems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXjgZR1qubs-XgXs" /><figcaption>Photo by <a href="https://unsplash.com/@joshriemer?utm_source=medium&amp;utm_medium=referral">Josh Riemer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most matrix problems can be intimidating at first glance. However, they are not that hard to solve at all! In this article, I will break down the steps to solve these problems starting with an overview of the matrix and how it is used.</p><p>First things first! Let’s get an overview of what a matrix is all about.</p><blockquote>What is a matrix?</blockquote><p>Definition from Wikipedia: “In mathematics, a <strong>matrix</strong> (plural <strong>matrices</strong>) is a rectangular <em>array </em>of numbers, symbols, or expressions, arranged in <em>rows</em> and <em>columns.”</em></p><p>In most places, the terms matrix and 2-D arrays are used interchangeably. A two-dimensional array can function exactly like a matrix. Two-dimensional arrays can be visualized as a table consisting of rows and columns.</p><h3>Examples of matrices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QJzBqqCu0SdvoXL5D-hXw.jpeg" /></figure><h3>Where do we see matrices in real life</h3><ul><li>Predominantly in database systems where data in tables are stored at intersections of a particular row and column.</li><li>In graphics where matrices represent pixels.</li><li>In a movie ticketing system (row-seat-number) or any booking system(bus/train/airlines) that uses row and column for seat identification.</li></ul><h3>Initialization and Traversal</h3><p>2D arrays are represented as a list of lists. Each list typically represents a row and each element of the list is a column. In this example, we will set up a theatre seating of 5 rows with 10 seats in each row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*ydBvObBnVXDdmfuMfLFMTA.png" /><figcaption>Initialize 2D array</figcaption></figure><p>The above can also be accomplished with a nested list comprehension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*_Az5cY44NibDQxzLd9rFgg.png" /><figcaption>Initialize a 2D array with list comprehension</figcaption></figure><p>Suppose, now we need to update that the last 2 rows are booked by setting a value of 1. This is how to do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*9LuocnK_BeYrRL5x7qtIDQ.png" /><figcaption>Update 2D Array</figcaption></figure><h3>Warm-up problem</h3><p>Now that we have covered the basics, let’s start with an easy problem.</p><h4>Transpose a matrix</h4><p>Transposing a matrix is to swap its row values with its column values.</p><pre>For every cell result[i][j] we need to replace the value with  input[j][i] <br>where input is the matrix to be transposed and <br>result is the placeholder for the transposed matrix</pre><p>Here’s the walkthrough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pbx9QVXuvOwTVe1kNhwQMg.jpeg" /><figcaption>Matrix Transpose</figcaption></figure><p>Here’s the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*FMnHqAXB4Gb2Tu0_krrv_Q.png" /><figcaption>matrixTranspose.py</figcaption></figure><p>Moving on — to <em>searching and updating</em> matrices.</p><p><a href="https://leetcode.com/problems/search-a-2d-matrix/"><strong>74. Search a 2D Matrix</strong></a></p><p>In this problem, we need to search for a value in a sorted matrix. A sorted matrix essentially means that the value at cell A[i][j] will always be greater than the values of all cells preceding it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09XStvMR2AxrZl41aq77Iw.jpeg" /><figcaption>Input and expected output</figcaption></figure><p><strong>Solution1</strong>: The brute-force approach to solving this is to iterate through each row and each column until we have found the target element or reached the end of the matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5634aaffcef124a46e2a654fa24cb5d/href">https://medium.com/media/f5634aaffcef124a46e2a654fa24cb5d/href</a></iframe><p>However, this is O(M*N) and does not utilize any of the structural information of the matrix provided in the problem description.</p><p>How can we do this better? In the matrix, every element in a row is sorted and all the rows are sorted in ascending order. What do we use to <em>search a value in sorted arrays</em>? Enter <strong>Binary Search</strong>!</p><p><strong>Solution2</strong>: Initialize start to 0 and end to M-1 where M= number of rows. Find the middle row and then apply a binary search to search for the target element in the row. If the target element is found, return True else modify the middle row as needed and continue the search till start ≤ end. So, the outer binary search searches for the row while the inner binary search searches for the element within a row. Here’s the walkthrough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVq6jAYY9JzNuA07T4jahw.jpeg" /><figcaption>binary search solution walkthrough</figcaption></figure><p>And here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b958773748c1947eae1a635b39d5fddb/href">https://medium.com/media/b958773748c1947eae1a635b39d5fddb/href</a></iframe><p><strong>Solution3</strong>: If we look closely at the matrix, there is an easier solution available. Notice that the<em> elements become smaller as we move left in a row and larger as we move down a column</em>. Utilizing this info we can traverse the matrix, changing direction depending on the value at a cell. Here’s the walkthrough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wev1Brpmkgb6b9zGpBiIOA.jpeg" /><figcaption>search Matrix — use direction</figcaption></figure><p>Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8db6089f6b657f3baa57882dec618c4c/href">https://medium.com/media/8db6089f6b657f3baa57882dec618c4c/href</a></iframe><p><strong>Note</strong>: We do not start from the <em>top left of the matrix but instead from the top right</em>. Why? Because, if we traverse from the top left, we can move to the right or move down and in both cases, values will only increase.</p><p><a href="https://leetcode.com/problems/search-a-2d-matrix-ii/"><strong>240. Search a 2D Matrix II</strong></a></p><p>This is pretty similar to the previous problem. Unlike the previous problem where all the elements were sorted, here a <em>preceding row can have higher values than the rows following it</em>. So we cannot use a binary search to determine a particular row for searching the target.</p><p>Let’s focus on the direction of the growth of the elements. The values increase downwards and values decrease as we move left. Using this info we can use the same algorithm as the above problem to solve this. Here’s the walkthrough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfwyELrkbRg9Gs6DzNrj1w.jpeg" /><figcaption>search matrix II walkthrough</figcaption></figure><p>Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcf83a3f20d04fbf47d645e7dbcb33e1/href">https://medium.com/media/bcf83a3f20d04fbf47d645e7dbcb33e1/href</a></iframe><p><a href="https://leetcode.com/problems/set-matrix-zeroes/"><strong>73. Set Matrix Zeroes</strong></a></p><p>My initial attempt to solve this problem was to traverse the array and if a 0 is found then update the entire row to 0. <em>Bad</em> idea! This will lose the information of which columns had a 0 value. So, before we actually update the array, we need something to maintain a record of which rows and columns contain 0.</p><p>Here’s the walkthrough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yKbYQfSXYfO5viccRXBqA.jpeg" /><figcaption>setZeroMatrix walkthrough</figcaption></figure><p>Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a56c22662e3413a3bd35f6e8edeb160/href">https://medium.com/media/3a56c22662e3413a3bd35f6e8edeb160/href</a></iframe><p>Now let’s look at traversing a matrix in different ways: <em>spirally</em> and <em>diagonally</em>.</p><p><a href="https://leetcode.com/problems/spiral-matrix/"><strong>54. Spiral Matrix</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*id-n48IIqx3nZvl_nRmncw.jpeg" /><figcaption>Problem input and expected output</figcaption></figure><p><strong>Note</strong>: There can be several ways to solve this problem. However, what I am sharing here seems the most intuitive solution. So let’s look at it step by step.</p><p><strong>Step1</strong>: Imagine we were solving this by hand in which case we can only move in 4 directions: we start with <strong>right</strong>, then move <strong>down</strong>, then <strong>left</strong> and finally <strong>up</strong>(followed by right again).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGU7q0S7vNINy9LTS8_WIQ.jpeg" /><figcaption>where can we move?</figcaption></figure><p><strong>Step2</strong>: How long do we keep doing this? Look at the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8NMxWVXU781MS0oHv0CHw.jpeg" /><figcaption>when do we stop traversing</figcaption></figure><p>Consider the matrix to be the <em>shrinking space</em> between the boundaries that are <em>moving in</em>. We know that we have traversed the entire matrix when these boundaries meet.</p><p><strong>Step3</strong>: Now we already discussed the directions to move in. Let’s look at how the boundaries change when we traverse in direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x65XnmekpBQJHHHA-_yfAQ.jpeg" /><figcaption>boundary changes when moving spirally</figcaption></figure><p><strong>Step4</strong>: Finally, how do we avoid traversing an element that we have already passed through before? To do this we maintain another matrix where we store the information of which positions are already traversed with a boolean value.</p><p>Here’s the code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4f29ae2aafee5c7a0fe1ba6ba61cd8/href">https://medium.com/media/5a4f29ae2aafee5c7a0fe1ba6ba61cd8/href</a></iframe><p><a href="https://leetcode.com/problems/spiral-matrix-ii/"><strong>59. Spiral Matrix II</strong></a></p><p>This problem is pretty similar to the first. Instead of traversing the matrix, here we need to build a square of ’n’ matrix. To do this we first build a matrix of n*n boolean values to store our result matrix and keep filling it as we move spirally — right →down →left →up →right….until we have filled values up to n*n.</p><p>Here’s the walkthrough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feeyjizQ8wBLgYYZp6YtwA.jpeg" /><figcaption>Generate matrix walkthrough</figcaption></figure><p>Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68614d2e5b2e7d4161e088561fc6fc75/href">https://medium.com/media/68614d2e5b2e7d4161e088561fc6fc75/href</a></iframe><p><a href="https://leetcode.com/problems/diagonal-traverse/"><strong>498. Diagonal Traverse</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz1Z3TRh8AEhOjbgflF-BA.jpeg" /><figcaption>Input and expected output</figcaption></figure><p><strong>Solution1</strong>: Solving this by hand we can see that we can move in 4 directions: Diagonally Up(<strong>DU</strong>), Diagonally Down(<strong>DD</strong>), Right(<strong>R</strong>) by 1 step, Down(<strong>D</strong>) by 1 step.</p><p>Now let’s see how the row and column ids change as we move in these directions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTVNpAZsGtB5K_MuoY-WFA.jpeg" /><figcaption>diagonal matrix walkthrough</figcaption></figure><p>Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da3cb365865eeab037fd8c70768c69b5/href">https://medium.com/media/da3cb365865eeab037fd8c70768c69b5/href</a></iframe><p><strong>Solution2</strong>: An easier solution exists which depends on the fact that the sum of the coordinates of every element in a diagonal will be the same.</p><p>Here is the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/597ef0ddf5a9466156a947c9469ae59c/href">https://medium.com/media/597ef0ddf5a9466156a947c9469ae59c/href</a></iframe><p>Thank you for the read and I hope this helped. Concluding with this quote from The Matrix, remember this when solving matrix problems or any problem :).</p><p><a href="https://matrix.fandom.com/wiki/Neo"><strong>Neo</strong></a>: What is the Matrix? <br><a href="https://matrix.fandom.com/wiki/Trinity"><strong>Trinity</strong></a>: The answer is out there, Neo. It’s looking for you, and <em>it will find you if you want it to.</em></p><h3>Resources</h3><ol><li><a href="https://www.ict.social/python/basics/multidimensional-lists-in-python">https://www.ict.social/python/basics/multidimensional-lists-in-python</a></li><li><a href="https://www.hackerearth.com/practice/data-structures/arrays/multi-dimensional/tutorial/">https://www.hackerearth.com/practice/data-structures/arrays/multi-dimensional/tutorial/</a></li><li><a href="https://www.hackerearth.com/practice/data-structures/arrays/multi-dimensional/tutorial/">https://www.hackerearth.com/practice/data-structures/arrays/multi-dimensional/tutorial/</a></li><li><a href="https://en.wikipedia.org/wiki/Matrix_(mathematics)">https://en.wikipedia.org/wiki/Matrix_(mathematics)</a></li><li><a href="https://leetcode.com/">https://leetcode.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=725096d122d9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/make-way-for-the-matrix-a-complete-guide-to-solving-2d-array-coding-problems-725096d122d9">Make Way For The Matrix — A Complete Guide to Solving 2D Array Coding Problems</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>