<?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"><channel><title><![CDATA[Amine's Blog]]></title><description><![CDATA[Amine's Blog]]></description><link>https://blog.saissihassani.com</link><generator>RSS for Node</generator><lastBuildDate>Sun, 26 Apr 2026 03:20:10 GMT</lastBuildDate><atom:link href="https://blog.saissihassani.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Two Sum Problem Solution]]></title><description><![CDATA[Two Sum problem is a common question that you can find in several problem solving websites and also in technical interviews.
Problem Statement (leetcode):
Given an array of integers nums and an integer target, return indices of the two numbers such t...]]></description><link>https://blog.saissihassani.com/two-sum-problem-solution</link><guid isPermaLink="true">https://blog.saissihassani.com/two-sum-problem-solution</guid><category><![CDATA[problem solving skills]]></category><category><![CDATA[Python]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Amine Saissi Hassani]]></dc:creator><pubDate>Fri, 04 Feb 2022 12:23:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1643976797835/zxLhUBaKH.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Two Sum problem is a common question that you can find in several problem solving websites and also in technical interviews.</p>
<h2 id="heading-problem-statement-leetcodehttpsleetcodecomproblemstwo-sum">Problem Statement (<a target="_blank" href="https://leetcode.com/problems/two-sum/">leetcode</a>):</h2>
<p>Given an array of integers <strong>nums</strong> and an integer <strong>target</strong>, return indices of the two numbers such that they add up to <strong>target</strong>.</p>
<p>You may assume that each input would have <strong>exactly one solution</strong>, and you may not use the same element twice.
You can return the answer in any order.</p>
<p>Example 1:</p>
<pre><code><span class="hljs-attr">Input:</span> <span class="hljs-string">nums</span> <span class="hljs-string">=</span> [<span class="hljs-number">2</span>,<span class="hljs-number">7</span>,<span class="hljs-number">11</span>,<span class="hljs-number">15</span>]<span class="hljs-string">,</span> <span class="hljs-string">target</span> <span class="hljs-string">=</span> <span class="hljs-number">9</span>
<span class="hljs-attr">Output:</span> [<span class="hljs-number">0</span>,<span class="hljs-number">1</span>]
<span class="hljs-attr">Explanation:</span> <span class="hljs-string">Because</span> <span class="hljs-string">nums[0]</span> <span class="hljs-string">+</span> <span class="hljs-string">nums[1]</span> <span class="hljs-string">==</span> <span class="hljs-number">9</span><span class="hljs-string">,</span> <span class="hljs-string">we</span> <span class="hljs-string">return</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>]<span class="hljs-string">.</span>
</code></pre><p>Example 2:</p>
<pre><code><span class="hljs-attr">Input:</span> <span class="hljs-string">nums</span> <span class="hljs-string">=</span> [<span class="hljs-number">3</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>]<span class="hljs-string">,</span> <span class="hljs-string">target</span> <span class="hljs-string">=</span> <span class="hljs-number">6</span>
<span class="hljs-attr">Output:</span> [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>]
</code></pre><p>Example 3:</p>
<pre><code><span class="hljs-attr">Input:</span> <span class="hljs-string">nums</span> <span class="hljs-string">=</span> [<span class="hljs-number">3</span>,<span class="hljs-number">3</span>]<span class="hljs-string">,</span> <span class="hljs-string">target</span> <span class="hljs-string">=</span> <span class="hljs-number">6</span>
<span class="hljs-attr">Output:</span> [<span class="hljs-number">0</span>,<span class="hljs-number">1</span>]
</code></pre><h2 id="heading-solutions">Solutions:</h2>
<h3 id="heading-solution-1-brute-force">Solution 1: Brute Force</h3>
<p>The first solution that came up in my mind is to check every possibility, so it will be a loop inside a loop to check every possibility.</p>
<p>The outer loop runs from i = 0 to i = n-1 and the inner loop runs from j = i + 1 to j = n - 1.</p>
<p>In each iteration in the inner loop, it checks if the sum of the array with the index of the outer loop and the array with the index of the inner loop equals the target.</p>
<p>If nums[i] + nums[j] is equal to target, return [i, j], else continue.</p>
<h4 id="heading-example">Example:</h4>
<p>The array: [15,11,7,2]. The target: 9.</p>
<p>The outer loop will start from  i = 0 to i = n - 1 (n is the length of the array which is in this case is 4) and the inner loop will start from  j = i + 1 to j = n - 1.</p>
<p>The first outer iteration, we start the first inner iteration and checking if the sum of the first index (0) of the array and the second index (0 + 1) of the array equal the target ( 15 + 11 = 26 != 9) and so on until we get these sums (15,11) (15,7) (15,2) in the first outer iteration, and at the second outer iteration we are going to do the same thing until we find the right sum (7,2) which will return the indexes: [2,3].</p>
<h4 id="heading-code">Code:</h4>
<h5 id="heading-python">Python:</h5>
<pre><code class="lang-py"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">twoSum</span>(<span class="hljs-params">self, nums: List[int], target: int</span>) -&gt; List[int]:</span>
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(nums)):
            <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range((<span class="hljs-number">1</span> + i), len(nums)):
                <span class="hljs-keyword">if</span> nums[i] + nums[j] == target:
                    <span class="hljs-keyword">return</span> [i, j]

        <span class="hljs-keyword">return</span> []
</code></pre>
<h5 id="heading-php">PHP:</h5>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>{

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@param</span> Integer[] $nums
     * <span class="hljs-doctag">@param</span> Integer $target
     * <span class="hljs-doctag">@return</span> Integer[]
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">twoSum</span>(<span class="hljs-params">$nums, $target</span>) </span>{
        $n = count($nums);
        <span class="hljs-keyword">for</span> ($i = <span class="hljs-number">0</span>; $i &lt; $n; $i++) {
            <span class="hljs-keyword">for</span> ($j = $i + <span class="hljs-number">1</span>; $j &lt; $n; $j++) {
                <span class="hljs-keyword">if</span> ($nums[$i] + $nums[$j] === $target) {
                    <span class="hljs-keyword">return</span> [$i, $j];
                }
            }
        }

        <span class="hljs-keyword">return</span> [];
    }
}
</code></pre>
<p>In the worst case, we will check every element, so its time complexity will be O(n^2).</p>
<h4 id="heading-complexity">Complexity:</h4>
<p> Time Complexity: O(n^2)</p>
<p> Space Complexity: O(1)</p>
<h3 id="heading-solution-2-optimized-solution-using-hashmap">Solution 2: Optimized Solution (Using Hashmap)</h3>
<p>After solving the problem with the time complexity of O(n^2), we can solve it in linear time. The idea is we use a Hashmap to store the visited elements in the array. the Hashmap key is the element of the array, and the Hashmap value will be the index of this element.</p>
<p>Declare a Hashmap (dictionary in python), some languages like java force you to declare which data types are the key and the value, in our case both are integers.</p>
<p>We will use one loop to iterate through each element in the array.</p>
<p>In each iteration we will check if the result of target - theCurrentElement is in the Hashmap as a key, else, we will insert theCurrentElement as a key in the Hashmap and its index as a value in the Hashmap.</p>
<p>And we will repeat this until we find it.</p>
<h4 id="heading-example">Example:</h4>
<p>The array: [27,3,7,11]. The target: 10.</p>
<p>We will declare <strong>seen</strong> as a Hashmap.</p>
<p>We will do a loop that iterate our array.</p>
<p>In the first iteration we will store the result of ( target: 10 - currentElement: 27) in a variable called remaining which will be in this case -17, then we will check if this number is in the <strong>seen</strong>, the <strong>seen</strong> is empty so we will store 27 in the <strong>seen</strong> as a key and the index 0 as a value.</p>
<p>In the second iteration we will see if the remaining is in the <strong>seen</strong>, in this case in 7, 7 is not in the <strong>seen</strong>, so we will store again in the <strong>seen</strong>, the current element 3 as key and its index 1 as a value.</p>
<p>In the third iteration we will see if the remaining 3 is in the <strong>seen</strong>, we already stored 3 in the <strong>seen</strong>, so now we can return the value of <strong>seen</strong> using the key of 3 and the index of the current element.</p>
<h4 id="heading-code">Code:</h4>
<h5 id="heading-python">Python:</h5>
<pre><code class="lang-py"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">twoSum</span>(<span class="hljs-params">self, nums: List[int], target: int</span>) -&gt; List[int]:</span>
        seen = {}
        <span class="hljs-keyword">for</span> i, value <span class="hljs-keyword">in</span> enumerate(nums):
            remaining = target - value
            <span class="hljs-keyword">if</span> remaining <span class="hljs-keyword">in</span> seen:
                <span class="hljs-keyword">return</span> [seen[remaining], i]

            seen[value] = i
</code></pre>
<h4 id="heading-complexity">Complexity:</h4>
<p> Time Complexity: O(n)</p>
<p> Space Complexity: O(n)</p>
]]></content:encoded></item></channel></rss>