<?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 Ryan Syed on Medium]]></title>
        <description><![CDATA[Stories by Ryan Syed on Medium]]></description>
        <link>https://medium.com/@syedtousifahmed?source=rss-543dfcdbca83------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xyD5Sj2GttNdWV8reUOTIA.jpeg</url>
            <title>Stories by Ryan Syed on Medium</title>
            <link>https://medium.com/@syedtousifahmed?source=rss-543dfcdbca83------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:37:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syedtousifahmed/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[Peak element Intuition]]></title>
            <link>https://syedtousifahmed.medium.com/peak-element-intuition-4b89ca34a9a?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b89ca34a9a</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Sat, 09 May 2020 12:40:17 GMT</pubDate>
            <atom:updated>2020-05-09T13:19:27.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OpEKpVf8842Y7_o8" /><figcaption>Photo by <a href="https://unsplash.com/@a_myth?utm_source=medium&amp;utm_medium=referral">Amith Nair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your goal is to find the peak element in a given collection of elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoT2Lhcfiq35Se5JX7ZP1A.png" /><figcaption>The peak elements are shown in green</figcaption></figure><p>If an element is greater or equal to its neighbors then it can be considered as a peak element.</p><blockquote>The naive approach is to just iterate through all the elements and find the element that is greater than or equal to its immediate neighbor as described in the question.</blockquote><p>What if I could randomly pick any element, can something be said about that element from checking its neighbors?</p><h3><strong>Possibility 1:</strong></h3><p>An element has two neighbors and both are less than or equal to it. This is then already the peak element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*SonIOUuklnIvOL_KFfPqZg.png" /><figcaption>Green is the current element and blue colored are the neighboring elements</figcaption></figure><h3>Possibility 2:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*VtayWT1ecVcOiH-X0SjV4g.png" /><figcaption>A neighbor on the left</figcaption></figure><p>One alternative is when you have a single neighbor on the left and the current element is greater than or equal to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*yX7l_8XUDMVj1dMfIK2Fnw.png" /><figcaption>A neighbor on the right</figcaption></figure><p>The other alternative is when you have a single neighbor on the right and the current element is greater than or equal to it.</p><h3>Possibility 3:</h3><blockquote>End of happy cases.</blockquote><p>Here you have a neighbor on the left that is greater than or equal to the current element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*goMdjPoBTJAdqGVpYTw_AQ.png" /><figcaption>Green is the current element, blue are the neighbors and yellow are the possible elements for the neighbor that is greater than current.</figcaption></figure><p>Can we safely move to that greater neighbor, hence, making a decision to eliminate the current element and all neighbors on the right?</p><p>Let’s find out. If yellow-colored elements are the two probable neighbors of the greater neighbor. Then if the below yellow neighbor is considered, then we can say this blue element is the peek, or else we can extend the same reasoning to the other greater yellow neighbor, where the blue element becomes the green element (current) and the greater yellow neighbor becomes the blue element (greater neighbor). Therefore, we can conclude, that the greater neighbor side should definitely have a peek element.</p><p>If this reminds you of the binary search, then you are spot on, as we are similarly eliminating half the search space in each step.</p><blockquote>This is the intuition behind finding a peak element in a collection. Will a peak element always exist? Definitely, as there has to be a maximum element.</blockquote><p>The code should not be a big leap from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nr3jWTxpptuZ7jZHFykEhQ.png" /><figcaption>Get coding !!</figcaption></figure><p>This kind of intuition is taught at <a href="https://www.scaler.com/">Scaler Academy</a>, where I am currently enrolled. The ideas in this post were introduced to me by <a href="https://www.linkedin.com/in/kshitij-mishra-a5779334/?originalSubdomain=in">Kshitij Mishra</a> who is an instructor at Scaler.</p><p>I hope to post more blogs on problem-solving intuition soon. Stay Tuned!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b89ca34a9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming: Climb to the top of the staircase with minimum cost]]></title>
            <link>https://syedtousifahmed.medium.com/dynamic-programming-climb-to-the-top-of-the-staircase-with-minimum-cost-dbd086770c31?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd086770c31</guid>
            <category><![CDATA[efficient]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 15:04:48 GMT</pubDate>
            <atom:updated>2020-03-24T15:04:48.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="climb to the top of this staircase with minimum penalty" src="https://cdn-images-1.medium.com/max/1024/0*tIofJSwET9JGtwjc" /><figcaption>Photo by <a href="https://unsplash.com/@srcharls?utm_source=medium&amp;utm_medium=referral">Roberto Carlos Roman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Frankly speaking, I would rather take the elevator, except when an interviewer forces you to take the stairs.</p><p>It isn’t fair that you have to exert so much physical effort. On top of it, you have to remember that every step has an underlying penalty.</p><h4>Rules of engagement:</h4><p>Your task is to reach the top of the staircase by incurring a minimum possible penalty. As a coder, your step count starts from zero. Your starting step can be step zero or step one, and you can move one or two-step forward.</p><p>Note: You will have at least two steps to take.</p><h3>Examples:</h3><p><strong>Input: </strong>[20, 10, 30]</p><p><strong>Output:</strong> As you can start from one, you will incur a penalty of 10 and then jump to the top.</p><p><strong>Input:</strong> [1, 3, 4, 2, 6]</p><p><strong>Output: </strong>You can incur a penalty of 1 &amp; 4 or 3 &amp; 2 and either way, with a minimum cost of 5 you can reach the top.</p><h3>Breaking it down</h3><p>Say suppose your problem looked like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBsFST0ADVHiVErQx8cWPQ.png" /><figcaption>Choices to get to the top</figcaption></figure><p>You can reach the top of the staircase from step 3 or step 4. Those are your only possible choices.</p><p>This seems like an optimization problem while making some choices and solving the problem (reaching the top) would require solving the subproblems: you need to know the best way to reach step 3 and step 4.</p><p>This problem reeks of dynamic programming.</p><h3><strong>Bottom-up approach</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcbZYK12DqnniaZTLoxAwA.png" /><figcaption>Computations at each step (literally)</figcaption></figure><p>The cost associated with step 0 and step 1 are straightforward as you can start from either of them. The minimum cost of any other step is calculated with the computation below:</p><blockquote>DP[i] = Cost[i] + min(Cost[i-1], Cost[i-2])</blockquote><p>Life is about tradeoffs or in words, this means to reach the current step n, it is imperative to decide if it is cheaper to come from step n-1 or step n-2.</p><p>Now, if you break the problem into its sub-problems, the only thing you need to worry about is the minimum cost of reaching a step 0, then step 1, then step 2… step n.</p><h3>Solution</h3><p>Solving the problem with a DP array of size n where n is the number of steps. The DP[i] holds the minimum cost/penalty to reach the step i.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472a43ced47ccd655916c6499d5b2fc3/href">https://medium.com/media/472a43ced47ccd655916c6499d5b2fc3/href</a></iframe><p>Here the time complexity is O(n) as we have to iterate over all the steps and space complexity is also O(n) as we have a DP array of size n.</p><h3>Reducing space complexity</h3><p>If you check out the source code of the solution above, then you will notice that:</p><blockquote>Only dp[i-1] and dp[i-2] are required for each i</blockquote><p>If we could use two variables to store these values, then we would not need an array of size n, where n is the number of steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b4977b431d9e938a5feeda9ff39926f/href">https://medium.com/media/9b4977b431d9e938a5feeda9ff39926f/href</a></iframe><p>Here, in the above solution, only the step i-1 and step i-2 data is stored and updated at the end of each iteration. This ensures the loop invariant of the last two-step data is maintained.</p><p>Also, the space complexity of the solution is now O(1) or constant space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd086770c31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Falsy club of JavaScript: Cheat Sheet]]></title>
            <link>https://syedtousifahmed.medium.com/falsy-club-of-javascript-cheat-sheet-19536b4d4ea4?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/19536b4d4ea4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Sat, 21 Sep 2019 11:59:27 GMT</pubDate>
            <atom:updated>2019-09-21T12:01:07.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Begx1e2VgWURELAhFHYcuA.png" /></figure><p>You may know about the Avengers, the A-team, the Expendables, the Fantastic Five or the X-men. However, none of these superheroes can get past the “Falsy” club. They are the values that can prevent your condition from passing, no matter how mighty you are.</p><p>A simple cheat sheet to help you remember them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19536b4d4ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming]]></title>
            <link>https://syedtousifahmed.medium.com/dynamic-programming-d9acbccd0834?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9acbccd0834</guid>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Thu, 30 Aug 2018 10:45:55 GMT</pubDate>
            <atom:updated>2018-08-30T10:47:23.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Not an interview from the tech giants goes by without a question from Dynamic Programming. It is kind of a fancy name for memorization or storing values for future references.</p><p>Would it take time for you to calculate the Fibonacci of 100?</p><p>Would it take much time to calculate the Fibonacci of 100, say you knew Fibonacci of 98 and 99?</p><p>Well if it did take you time to answer the latter question, then this article is not gonna do you any good(Pssst … consider redoing high school maths)</p><p>If you even come across a problem where in order to solve for the given input you have to solve the problem for sub-problems of the given input, then it is a classic case of dynamic programming.</p><p>For integers it could be to solve for smaller integers. For a string it could be to solve for a set of sub strings etc.</p><p>To demonstrate this I would like to take the classic example of Fibonacci numbers. If you would like a primer of the recursive solution or Fibonacci check out: <a href="https://medium.com/@syedtousifahmed/fibonacci-iterative-vs-recursive-5182d7783055">Fibonacci Iterative vs. Recursive</a>.</p><h4>C++ code:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/602662cf5827c6135891130b40322cfb/href">https://medium.com/media/602662cf5827c6135891130b40322cfb/href</a></iframe><h4>Time complexity:</h4><p>As we have seen in the post <a href="https://medium.com/@syedtousifahmed/fibonacci-iterative-vs-recursive-5182d7783055">Fibonacci Iterative vs. Recursive</a> , the recursive solution takes O(2 ^ n) time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AeRe16QGs8SJj7QP6zVrUw.png" /><figcaption>Recursion tree for Fibonacci of 6</figcaption></figure><p>If we look at the recursion tree then as the recursive function goes along the longest branch of the tree, all the required Fibonacci numbers are calculated and stored in the array, therefore, further calls to those values do not spawn any new trees and therefore the time taken is as below:</p><pre>T(n) = T(n-1) + c<br>     = T(n-2) + 2c<br>     = T(n-3) + 3c<br>     = T(n-k) + kc</pre><pre>Let&#39;s find the value of k for which: n - k = 0<br>k = n</pre><pre>T(n) = T(0) + nc<br>     = nc + 1</pre><pre>i.e. time take by fibonacci recursive with memorization / Dynamic Programming is O(n).</pre><h4>Space Complexity:</h4><p>The space complexity for the array is O(n) and for the recursive call stack is also O(n). Hence the total space complexity is O(n).</p><p>Why go to such lengths when we can find the solution of Fibonacci numbers iteratively in O(n) time and O(1) space?</p><p>The space trade off using Dynamic Programming let’s us calculate a pre-calculated value in O(1) time. Hence in case of real time systems, this could be very beneficial and even desired.</p><p>For more posts like this, check out my other content and follow me. Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9acbccd0834" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hashing and Hash maps]]></title>
            <link>https://syedtousifahmed.medium.com/hashing-and-hash-maps-1cbd280ab134?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cbd280ab134</guid>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[hashing]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Thu, 30 Aug 2018 08:21:38 GMT</pubDate>
            <atom:updated>2018-08-30T10:12:12.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NK4VyFvQQChPg2wX" /><figcaption>We are definitely not gonna talk about that :P</figcaption></figure><p>Say you wanted to code up an implementation of a dictionary of English words, then how would you approach this problem</p><h4>Approach 1:</h4><p>Using a LinkedList or an Array</p><p>In order to check the definition or presence of a word, we would have to iterate over all the words sequentially, and the time complexity would be O(n).</p><h4>Approach 2:</h4><p>Using a Balanced Binary Search Tree</p><p>In case of a Balanced Binary Search Tree, the longest node would be at a depth of log N, hence the time complexity would be O(log n)</p><h4>Approach 3:</h4><p>What if we could access the key using an index like an array, then the time taken would be O(1). Presenting Hash maps , they use an array with a hash code as index to store and retrieve the elements quickly.</p><p>Say we wanted to store “Hello” and “Bye” in our map, then we could use their lengths and store them at that corresponding index and their definitions in another array with the same index.</p><blockquote>However, if we then planned to store a word like “Bingo”, then we would be in a pickle (Same would happen if we did try to store “Pickle”). This is referred to as a collision.</blockquote><p>In order to prevent collisions we can instead store linked lists in the array so that elements with the same hash code would be present in the same list.</p><p>But what about space wastage?</p><p>Sure, if we used the length as a hash code, then really long words would be stored at a distant index and we would also be wasting a lot of space. Instead we have to figure out how we could generate better hash codes.</p><p>But what about huge memory requirement?</p><p>What if we kept generating unique hash-codes, then won’t our arrays will have to be really long. The answer is no. We can have a desired/fix size of our array and then take a modulus of the generated hash code with our array size, resulting in an index within the array.</p><p>But why is the word length inadequate as our hash function?</p><p>The entries with same hash codes are stored in the same linked list. These are called buckets as they group together entries with the same index. Now say for common English words of letter 4, 5, 6 etc. the buckets would be really large and therefore finding the definition would not be a constant time operation. Therefore we would need a better hash function than our word length.</p><p>So what constitutes a good hash function?</p><p>A hash function would be considered good if the values produced by it are distributed over a large range of values so that each element can be found in a few comparisons.</p><p>I will write another post about hashing in the future, so if you enjoyed this post, then do check it out and other content by me. Also, don’t forget to follow me so that you don’t miss any post. Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cbd280ab134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular exponentiation]]></title>
            <link>https://syedtousifahmed.medium.com/modular-exponentiation-4a48e4f47ec3?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a48e4f47ec3</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Thu, 30 Aug 2018 06:49:22 GMT</pubDate>
            <atom:updated>2018-08-30T06:49:44.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X8DF7X2enMN4TUul" /><figcaption>“architectural photography of white building” by <a href="https://unsplash.com/@bixphotos?utm_source=medium&amp;utm_medium=referral">Benjamin Bousquet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Say you are required to code up:<br>(a ^ b) % c</p><p>Now why do “% c” after exponentiation, because a ^ b will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.</p><h4>Property 1:</h4><blockquote>Also (m * n) % p has a very interesting property:<br>(m * n) % p =((m % p) * (n % p)) % p</blockquote><h4>Property 2:</h4><blockquote>if b is even:<br>(a ^ b) % c = ((a ^ b/2) * (a ^ b/2))%c → this suggests divide and conquer</blockquote><blockquote>if b is odd:<br>(a ^ b) % c = (a * (a ^( b-1))%c</blockquote><h4>Property 3:</h4><blockquote>If we have to return the mod of a negative number x whose absolute value is less than y:<br>then (x + y) % y will do the trick</blockquote><h4>Note:</h4><p>also as the product of (a ^ b/2) * (a ^ b/2) and a * (a ^( b-1) may cause overflow, hence we must be careful about those scenarios</p><h3>C++ code:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58a47196ffceb564e3de68f901d70026/href">https://medium.com/media/58a47196ffceb564e3de68f901d70026/href</a></iframe><p>For more posts like this follow me and do check out my other content. Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a48e4f47ec3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fibonacci Iterative vs. Recursive]]></title>
            <link>https://syedtousifahmed.medium.com/fibonacci-iterative-vs-recursive-5182d7783055?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/5182d7783055</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[backtracking]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Thu, 30 Aug 2018 04:23:37 GMT</pubDate>
            <atom:updated>2021-02-21T06:50:01.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Fibonacci series:</p><p>fib(n) = fib(n-1) + fib(n-2) → for n &gt; 1<br>fib(n) = 1→ for n = 0, 1</p><p>Fibonacci can be solved iteratively as well as recursively</p><h4>Recursive approach:</h4><p>The recursive approach seems to be much simpler and smaller, but there is a caveat, as it is calculating the Fibonacci of a number multiple times.</p><h4>Time Complexity:</h4><p>The time complexity of the iterative code is linear, as the loop runs from 2 to n, i.e. it runs in O(n) time</p><p>Calculating the time complexity of the recursive approach is not so straightforward, so we are going to dive in</p><pre>fib(n):<br>    if n &lt;= 1<br>        return 1<br>    return fib(n - 1) + fib(n - 2)</pre><p>for n &gt; 1:<br>T(n) = T(n-1) + T(n-2) + 4 (1 comparison, 2 subtractions, 1 addition)</p><p>Let’s say c = 4 and try to first establish a lower bound by approximating that T(n-1) ~ T(n-2) , though T(n-1) ≥ T(n-2), hence lower bound</p><pre>T(n) = T(n-1) + T(n-2) + c<br>     = 2T(n-2) + c    //from the approximation T(n-1) ~ T(n-2)<br>     = 2*(2T(n-4) + c) + c<br>     = 4T(n-4) + 3c<br>     = 8T(n-6) + 7c<br>     = 2^k * T(n - 2k) + (2^k - 1)*c</pre><pre>Let&#39;s find the value of k for which: n - 2k = 0<br>k = n/2</pre><pre>T(n) = 2^(n/2) * T(0) + (2^(n/2) - 1)*c<br>     = 2^(n/2) * (1 + c) - c</pre><pre>i.e. T(n) ~ 2^(n/2)</pre><p>now for the upper bound, we can approximate T(n-2) ~ T(n-1) as T(n-2) ≤ T(n-1)</p><pre>T(n) = T(n-1) + T(n-2) + c<br>     = 2T(n-1) + c    //from the approximation T(n-1) ~ T(n-2)<br>     = 2*(2T(n-2) + c) + c<br>     = 4T(n-2) + 3c<br>     = 8T(n-3) + 7c<br>     = 2^k * T(n - k) + (2^k - 1)*c</pre><pre>Let&#39;s find the value of k for which: n - k = 0<br>k = n</pre><pre>T(n) = 2^n * T(0) + (2^n - 1)*c<br>     = 2^n * (1 + c) - c</pre><pre>i.e. T(n) ~ 2^n</pre><p>Hence the time taken by recursive Fibonacci is O(2^n) or exponential.</p><h4>Space Complexity:</h4><p>For the iterative approach, the amount of space required is the same for fib(6) and fib(100), i.e. as N changes the space/memory used remains the same. Hence it’s space complexity is O(1) or constant.</p><p>For Fibonacci recursive implementation or any recursive algorithm, the space required is proportional to the maximum depth of the recursion tree, because, that is the maximum number of elements that can be present in the implicit function call stack.</p><p>Below is a diagrammatic representation of the Fibonacci recursion tree for fib(6):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AeRe16QGs8SJj7QP6zVrUw.png" /><figcaption>Recursion tree for Fibonacci of 6</figcaption></figure><p>As you can see the maximum depth is proportional to the N, hence the space complexity of Fibonacci recursive is O(N).</p><p>If you like the post and want to learn more about Data Structures and Algorithms, Low-Level Design and High-Level Design to crack top product company interviews and get into FAANG, then I would highly recommend joining <a href="https://www.scaler.com/academy?unlock_code=TOUS7321">Scaler</a>, where I am an Alumni and owe a lot of my success to them. Their curriculum is highly structured with teachers who are ex-Googlers, ex-Media.net etc. employees. You also get mentorship from the very best, working in your dream tech companies like FAANG. If you use the link my link to join <a href="https://www.scaler.com/academy?unlock_code=TOUS7321">Scaler</a>, then you will get a course discount of Rs. 10,000 and I will get a cashback of the same amount. Do check out their course and take advantage of the classes provided by them to boost your career from the comfort of your home.</p><p>For more tips and algorithms check out my other content. Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5182d7783055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculating the factorial of number recursively (Time and Space analysis)]]></title>
            <link>https://syedtousifahmed.medium.com/calculating-the-factorial-of-number-recursively-time-and-space-analysis-dd47ac5f2607?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd47ac5f2607</guid>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[factorials]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 11:52:25 GMT</pubDate>
            <atom:updated>2021-02-21T06:48:56.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HJYGrg1nB3ppQdv0" /><figcaption>“grayscale photo of wood trunks” by <a href="https://unsplash.com/@johnwestrock?utm_source=medium&amp;utm_medium=referral">John Westrock</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The factorial of a number is defined as:</p><p>f(n) = n * f(n-1) → for all n &gt;0<br>f(0) = 1 → for n = 0</p><pre>factorial(n):<br>    if n is 0<br>         return 1<br>    return n * factorial(n-1)</pre><h4>C++ code:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3663dc3c75064192be9f5f9bde4e48fe/href">https://medium.com/media/3663dc3c75064192be9f5f9bde4e48fe/href</a></iframe><h3>Time complexity</h3><p>If we look at the pseudo-code again, added below for convenience. Then we notice that:</p><ul><li>factorial(0) is only comparison (1 unit of time)</li><li>factorial(n) is 1 comparison, 1 multiplication, 1 subtraction and time for factorial(n-1)</li></ul><pre>factorial(n):<br>    if n is 0<br>         return 1<br>    return n * factorial(n-1)</pre><p>From the above analysis we can write:</p><p>T(n) = T(n — 1) + 3<br>T(0) = 1</p><pre>T(n) = T(n-1) + 3<br>     = T(n-2) + 6<br>     = T(n-3) + 9<br>     = T(n-4) + 12<br>     = ...<br>     = T(n-k) + 3k</pre><pre>as we know T(0) = 1<br>we need to find the value of k for which n - k = 0, k = n</pre><pre>T(n) = T(0) + 3n , k = n<br>     = 1 + 3n</pre><pre>that gives us a time complexity of O(n)</pre><h3>Space complexity</h3><p>For every call to the recursive function, the state is saved onto the call stack, till the value is computed and returned to the called function.</p><p>Here we don’t assign an explicit stack, but an implicit call stack is maintained</p><p>f(6) → f(5) → f(4) → f(3) → f(2) → f(1) → <strong>f(0)</strong><br>f(6) → f(5) → f(4) → f(3) → f(2) →<strong> f(1)</strong><br>f(6) → f(5) → f(4) → f(3) → <strong>f(2)</strong><br>f(6) → f(5) → f(4) → <strong>f(3)</strong><br>f(6) → f(5) → <strong>f(4)</strong><br>f(6) → <strong>f(5)</strong><br><strong>f(6)</strong></p><p>The function in bold is the one currently being executed. As you can see for f(6) a stack of 6 is required till the call is made to f(0) and a value is finally computed. Hence for factorial of N, a stack of size N will be <em>implicitly </em>allocated for storing the state of the function calls.</p><p>The space complexity of recursive factorial implementation is O(n)</p><p>If you like the post and want to learn more about Data Structures and Algorithms, Low-Level Design and High-Level Design to crack top product company interviews and get into FAANG, then I would highly recommend joining <a href="https://www.scaler.com/academy?unlock_code=TOUS7321">Scaler</a>, where I am an Alumni and owe a lot of my success to them. Their curriculum is highly structured with teachers who are ex-Googlers, ex-Media.net etc. employees. You also get mentorship from the very best, working in your dream tech companies like FAANG. If you use the link my link to join <a href="https://www.scaler.com/academy?unlock_code=TOUS7321">Scaler</a>, then you will get a course discount of Rs. 10,000 and I will get a cashback of the same amount. Do check out their course and take advantage of the classes provided by them to boost your career from the comfort of your home.</p><p>For more coding related tips and walkthroughs check out my content. Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd47ac5f2607" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to find the index of the next and previous element of a circular array]]></title>
            <link>https://syedtousifahmed.medium.com/how-to-find-the-index-of-the-next-and-previous-element-of-a-circular-array-e47f021662bd?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/e47f021662bd</guid>
            <category><![CDATA[circular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 05:35:34 GMT</pubDate>
            <atom:updated>2018-08-29T05:35:34.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fdXiXEF_Bf8djCpu" /><figcaption>“low angle photography of white concrete building” by <a href="https://unsplash.com/@carlnewton?utm_source=medium&amp;utm_medium=referral">Carl Newton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have an array that is circular, i.e. the next element of the last element is the first element.</p><p>To find the next and the previous index we are going to rely of the modulus operator.</p><pre>if N is the array element, curr is the current index in a 0-index array, then<br>next = (curr + 1) % N</pre><blockquote>if curr is not the last element then (curr + 1) % N == curr + 1, hence the next index, however if (curr + 1) == N, i.e. the current element is the last index, then (curr + 1) % N == 0, therefore the next element will be the first element of the array.</blockquote><pre>if N is the array element, curr is the current index in a 0-index array, then<br>prev = (curr + N - 1) % N</pre><blockquote>if current is not the first element of the array, then (curr + N — 1) % N == (curr — 1) % N + N % N == curr — 1</blockquote><blockquote>However if curr == 0 , i.e. it is the first element, then (curr + N — 1) % N == (N — 1) % N == N — 1 , i.e. the index of the last element of the array.</blockquote><p>This article demonstrated how we can craftily use the modulus operator to cover the corner cases while finding the next and previous element in a circular array. For more code walk through and coding tips, check out my other content. Happy coding !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e47f021662bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search and finding count in a sorted array]]></title>
            <link>https://syedtousifahmed.medium.com/binary-search-and-finding-count-in-a-sorted-array-d150949eeb2f?source=rss-543dfcdbca83------2</link>
            <guid isPermaLink="false">https://medium.com/p/d150949eeb2f</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[cplusplus]]></category>
            <dc:creator><![CDATA[Ryan Syed]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 03:47:44 GMT</pubDate>
            <atom:updated>2018-08-29T03:47:44.274Z</atom:updated>
            <content:encoded><![CDATA[<p>If you had the find an element in a sorted array, the first thing that should pop in your mind is binary search. Now a simple algorithm for binary search is mentioned below:</p><pre>given a sorted array A and a key to be found in the array<br>lo = 0<br>hi = A.length - 1<br>iterate till: lo &lt;= hi<br>     mid = lo + (hi - lo)/2 <br>     //better than mid = (lo + hi)/2, because it avoids possible<br>     //overflow</pre><pre>     if A[mid] &gt; key<br>          hi = mid - 1<br>     else if A[mid] &lt; key<br>          lo = mid + 1<br>     else<br>          return mid<br>return -1 // not found</pre><h4>C++ code:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1550e856d767d2292be371c659da6006/href">https://medium.com/media/1550e856d767d2292be371c659da6006/href</a></iframe><p>Now to find the left most element or the right most element we have to tweak the binary search when the key is found to continue looking left or right.</p><p>Let’s look at the pseudo code to find the leftmost occurrence below:</p><pre>result = -1;<br>...<br>...<br>if A[mid] == key<br>    result = mid<br>    hi = mid - 1;<br>...<br>...</pre><pre>return result;</pre><p>Similarly the code for the rightmost occurrence is as below:</p><pre>result = -1;<br>...<br>...<br>if A[mid] == key<br>    result = mid<br>    lo = mid + 1;<br>...<br>...</pre><pre>return result;</pre><h4>C++ code:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ccb4ad262a598657b563c8e4a6dfc2/href">https://medium.com/media/10ccb4ad262a598657b563c8e4a6dfc2/href</a></iframe><p>Now to find the total count all we have to do is find the left most and the right most element and return the difference plus one.</p><pre>count = right - left + 1</pre><h4>C++ code:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d126d26aa431a29f4add3c67f89229e/href">https://medium.com/media/5d126d26aa431a29f4add3c67f89229e/href</a></iframe><p>If you enjoyed this problem walk-through check out more of my content. Happy coding !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d150949eeb2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>