<?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 Studylearnandfun on Medium]]></title>
        <description><![CDATA[Stories by Studylearnandfun on Medium]]></description>
        <link>https://medium.com/@studylearnandfun?source=rss-070deb50d45d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cfFf1x1RK1_L4z6L5rGKJg.jpeg</url>
            <title>Stories by Studylearnandfun on Medium</title>
            <link>https://medium.com/@studylearnandfun?source=rss-070deb50d45d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 06:19:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@studylearnandfun/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[Longest Common Prefix — LeetCode 14]]></title>
            <link>https://medium.com/@studylearnandfun/longest-common-prefix-leetcode-14-b11091c7a6bf?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b11091c7a6bf</guid>
            <category><![CDATA[longest-common-prefix]]></category>
            <category><![CDATA[leetcode-problem-14]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[problems]]></category>
            <category><![CDATA[problem-14]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 19:46:02 GMT</pubDate>
            <atom:updated>2026-11-13T19:46:02.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*rb7jOzgR5sdxQ0xEbYy2Bg.png" /></figure><p>A beginner-friendly guide to finding the starting letters shared by every string, with a visual explanation, a complete dry run, and optimal Python, Java, and PHP solutions.</p><p><strong>Strings | Array | Interview Preparation | Reading time: 12–15 minutes</strong></p><h3>1. Introduction</h3><p>Imagine that you have three words: <strong>flower</strong>, <strong>flow</strong> and <strong>flight</strong>. All three words begin with the letters <strong>f</strong> and <strong>l</strong>. However, their next letters are different. The longest starting part shared by all three words is therefore <strong>“fl”</strong>.</p><p>This is exactly what the <em>Longest Common Prefix</em> problem asks us to find. A prefix is simply a group of characters at the beginning of a word. Our job is to find the longest prefix that appears at the beginning of every string in the given list.</p><p>This problem is useful because it teaches us how to compare strings, inspect characters by position, and stop as soon as a mismatch is found. Similar ideas appear in search suggestions, grouping words, autocomplete systems and text processing.</p><p>By the end of this tutorial, you will understand the problem, follow the algorithm by hand, and be able to implement it in Python, Java and PHP.</p><h3>2. Problem Statement</h3><p><strong>Given an array of strings </strong><strong>strs, write a function to find the longest common prefix string amongst the strings.</strong></p><p>If there is no common prefix, return an empty string &quot;&quot;.</p><p>In simple words: look at the beginning of every word and find the longest sequence of letters that is exactly the same in all of them. The matching letters must start at position zero; letters that appear later in a word do not count.</p><h3>What does “prefix” mean?</h3><p>A prefix is a continuous group of characters taken from the beginning of a string. For example, the prefixes of &quot;computer&quot; include &quot;c&quot;, &quot;co&quot;, &quot;com&quot; and &quot;comp&quot;. The word &quot;put&quot; is not a prefix because it does not start at the beginning.</p><h3>Constraints</h3><ul><li>1 &lt;= strs.length &lt;= 200</li><li>0 &lt;= strs[i].length &lt;= 200</li><li>strs[i] contains only lowercase English letters if it is non-empty.</li></ul><p><strong>Important:</strong> A string in the array may be empty. If even one string is empty, there cannot be a non-empty common prefix, so the answer must be &quot;&quot;.</p><h3>3. Examples Explained</h3><h3>Example 1</h3><p><strong>Input:</strong> strs = [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;]</p><p><strong>Output:</strong> &quot;fl&quot;</p><p>Compare the strings from left to right:</p><ol><li>First character: f, f, f — all match.</li><li>Second character: l, l, l — all match.</li><li>Third character: o, o, i — not all match.</li></ol><p>We must stop at the first mismatch. The common starting part is &quot;fl&quot;.</p><h3>Example 2</h3><p><strong>Input:</strong> strs = [&quot;dog&quot;, &quot;racecar&quot;, &quot;car&quot;]</p><p><strong>Output:</strong> &quot;&quot;</p><p>The first characters are d, r and c. They are already different, so there is no common prefix. Return an empty string.</p><h3>4. Understanding the Problem</h3><h3>What are we given?</h3><p>We are given a list (array) containing one or more strings. Each string is a sequence of characters, such as &quot;flower&quot; or &quot;flow&quot;.</p><h3>What do we need to find?</h3><p>We need the longest sequence of characters that every string shares <strong>from the very beginning</strong>.</p><h3>Important observations</h3><ul><li>Every character in the answer must match at the same position in every string.</li><li>We must stop as soon as one string has a different character.</li><li>We must also stop if we reach the end of any string.</li><li>If the first character does not match, the answer is empty.</li></ul><h3>A simple real-world analogy</h3><p>Think of several people reading words aloud, one letter at a time. They all say “f”, then all say “l”. At the next letter, one person says “i” while the others say “o”. The group can agree only on “fl”. That shared beginning is the longest common prefix.</p><h3>5. Important Concepts Required</h3><h3>1. Array of strings</h3><p>An array is a collection of values stored together. Here, each value is a word.</p><pre>strs = [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;]</pre><p>We use the array to visit every word and compare its characters.</p><h3>2. String indexing</h3><p>Each character in a string has a position called an index. In most of the languages used here, indexing starts at zero.</p><pre>word = &quot;flow&quot;<br># index:     0  1  2  3<br># character: f  l  o  w</pre><p>So word[0] is &#39;f&#39;, and word[1] is &#39;l&#39;.</p><h3>3. Loops and comparison</h3><p>A loop repeats an action. We use one loop to move through character positions and another to check that position in every string. A comparison checks whether two characters are equal.</p><pre>if strs[0][position] != strs[1][position]:<br>    # These two characters are different.</pre><p>The actual solution checks all strings, not just the first two.</p><h3>6. Approaches to Solve the Problem</h3><h3>Approach 1: Brute Force — Try Prefixes One by One</h3><p><strong>Basic idea:</strong> Start with a prefix of length one, then length two, then length three, and so on. For each candidate, check whether every string starts with that candidate. Keep the longest candidate that works. Stop when a candidate fails.</p><h4>Step-by-step example</h4><p>For [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;]:</p><ol><li>Try &quot;f&quot;. All words start with it, so keep it.</li><li>Try &quot;fl&quot;. All words start with it, so keep it.</li><li>Try &quot;flo&quot;. &quot;flight&quot; does not start with it, so stop.</li></ol><p>The answer is &quot;fl&quot;.</p><h4>Pseudocode</h4><pre>Find the length of the shortest string.<br>Set answer to an empty string.<br>For each possible prefix length from 1 to shortest length:<br>    Take that many characters from the first string.<br>    Check whether every string starts with this candidate.<br>    If all strings match:<br>        Save the candidate as the answer.<br>    Otherwise:<br>        Stop checking longer candidates.<br>Return answer.</pre><h4>Fully commented Python code</h4><pre>def longestCommonPrefix(strs):<br>    # The shortest word puts a limit on how long<br>    # a common prefix can possibly be.<br>    shortest_length = min(len(word) for word in strs)<br>    # This will store the longest prefix that works.<br>    answer = &quot;&quot;<br>    # Try prefix lengths 1, 2, 3, ... up to the shortest word.<br>    for length in range(1, shortest_length + 1):<br>        # Take the first &#39;length&#39; characters from the first word.<br>        candidate = strs[0][:length]<br>        # Check whether every word begins with this candidate.<br>        all_match = True<br>        for word in strs:<br>            if not word.startswith(candidate):<br>                all_match = False<br>                break<br>        # If every word matched, this is our new best answer.<br>        if all_match:<br>            answer = candidate<br>        else:<br>            # A longer prefix cannot work after a shorter one fails.<br>            break<br>    return answer</pre><p><strong>Time complexity:</strong> In the worst case, this approach can check many candidate prefixes against many strings. With straightforward prefix comparisons, a safe upper bound is O(N × L²), where N is the number of strings and L is the length of the shortest string.</p><p><strong>Space complexity:</strong> Up to O(L) for candidate and answer strings, depending on the language&#39;s substring behavior.</p><p><strong>Advantages:</strong> Very easy to understand because it tests prefixes in increasing order.</p><p><strong>Disadvantages:</strong> It repeats comparisons for characters that were already checked in shorter prefixes.</p><h3>Approach 2: Optimal — Vertical Scanning</h3><p><strong>Core intuition:</strong> Instead of building and checking many candidate prefixes, compare all strings one character position at a time. Start at position zero. If every string has the same character at that position, move to the next position. The first mismatch tells us exactly where the common prefix ends.</p><p><strong>Why this is preferable:</strong> Each character position is examined only until the first mismatch or the end of the shortest string. We do not repeat the full prefix comparison for every possible prefix length.</p><h4>Algorithm step by step</h4><ol><li>Choose the first string as the reference word.</li><li>Visit its characters from left to right, using a position counter.</li><li>For the current position, compare the reference character with the character at the same position in every other string.</li><li>If a string ends or a character differs, return the part of the reference word before this position.</li><li>If all positions match, return the whole reference word.</li></ol><h4>Pseudocode</h4><pre>If the input list is empty:<br>    Return an empty string.<br>Use the first string as the reference word.<br>For each character position in the reference word:<br>    For each string in the list:<br>        If this string has ended:<br>            Return the reference word before this position.<br>        If its character at this position differs from the reference:<br>            Return the reference word before this position.<br>Return the complete reference word.</pre><h4>Why does it work?</h4><p>A common prefix must match at position zero, then position one, then position two, and so on without skipping a position. Therefore, the first position where any string differs is the exact point where the shared prefix ends. No character after that position can extend the common prefix.</p><p><strong>Time complexity:</strong> O(N × L) in the worst case, where N is the number of strings and L is the length of the shortest string (or reference string if all strings are at least that long). More precisely, the algorithm performs at most one comparison per string per visited position.</p><p><strong>Auxiliary space complexity:</strong> O(1), excluding the returned prefix. The algorithm uses only a few counters and references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*T3YFEihHPjJGhA50nFhr8A.png" /><figcaption>Longest common prefix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*_szwl5zkkJpcGFfR_fVA7g.png" /></figure><h3>9. Pseudocode</h3><pre>FUNCTION longestCommonPrefix(list of words):<br>    IF the list is empty:<br>        RETURN &quot;&quot;<br>    reference = first word in the list<br>    FOR each position from 0 to the end of reference:<br>        expectedCharacter = character at this position in reference<br>        FOR each word in the list:<br>            IF position is beyond the end of word:<br>                RETURN reference from beginning up to this position<br>            IF word&#39;s character at this position is not expectedCharacter:<br>                RETURN reference from beginning up to this position<br>    RETURN reference</pre><p>The pseudocode is intentionally written in plain language. The Python, Java and PHP versions below follow the same checks.</p><h3>10. Code Implementations in Multiple Programming Languages</h3><h3>Python</h3><p><strong>Approach:</strong> Optimal vertical scanning.</p><p><strong>Explanation:</strong> We use the first word as the reference. For each character in it, we inspect that same position in every word. If a word is too short or its character is different, we return the reference word up to the current position.</p><p><strong>Complete Python code</strong>Copy code</p><pre>class Solution:<br>    def longestCommonPrefix(self, strs):<br>        # The problem guarantees at least one string,<br>        # but this check also makes the function safe for an empty list.<br>        if not strs:<br>            return &quot;&quot;<br>        # Use the first word as our reference for comparison.<br>        first_word = strs[0]        # Move through the reference word one character at a time.<br>        for position in range(len(first_word)):<br>            # This is the character every other word must have here.<br>            expected_character = first_word[position]<br>            # Compare this position in every word.<br>            for word in strs:<br>                # If this word has no character at this position,<br>                # it is shorter than the reference word.<br>                if position &gt;= len(word):<br>                    # Return all reference characters before this position.<br>                    return first_word[:position]<br>                # If the character is different, the common prefix ends here.<br>                if word[position] != expected_character:<br>                    return first_word[:position]<br>        # If no mismatch was found, the entire first word is common.<br>        return first_word<br><br># Example:<br>solution = Solution()<br>print(solution.longestCommonPrefix([&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;]))<br># Output: fl</pre><p><strong>Example execution:</strong> Input: [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;] → Output: &quot;fl&quot;.</p><p><strong>Complexity:</strong> Time O(N × L); auxiliary space O(1), excluding the returned substring.</p><h3>Java</h3><p><strong>Approach:</strong> Optimal vertical scanning.</p><p><strong>Explanation:</strong> Java strings use zero-based character positions too. We read the reference character with charAt(position), then compare it with the same position in every string. We check the string length first so that we never try to read a character beyond its end.</p><p><strong>Complete Java code</strong>Copy code</p><pre>class Solution {<br>    public String longestCommonPrefix(String[] strs) {<br>        // Safety check: if there are no words, there is no common prefix.<br>        if (strs == null || strs.length == 0) {<br>            return &quot;&quot;;<br>        }<br>        // Use the first word as the reference word.<br>        String firstWord = strs[0];<br>        // Visit each character position in the reference word.<br>        for (int position = 0; position &lt; firstWord.length(); position++) {<br>            // Store the character that all words must match at this position.<br>            char expectedCharacter = firstWord.charAt(position);<br>            // Check this same position in every word.<br>            for (String word : strs) {<br>                // If the current word is too short, the prefix ends here.<br>                if (position &gt;= word.length()) {<br>                    return firstWord.substring(0, position);<br>                }<br>                // If the character does not match, return the prefix so far.<br>                if (word.charAt(position) != expectedCharacter) {<br>                    return firstWord.substring(0, position);<br>                }<br>            }<br>        }<br>        // Every character of the reference word matched in all words.<br>        return firstWord;<br>    }<br>}<br>// Example use:<br>// Solution solution = new Solution();<br>// System.out.println(solution.longestCommonPrefix(<br>//     new String[] {&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;}<br>// ));<br>// Output: fl</pre><p><strong>Example execution:</strong> Input: [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;] → Output: &quot;fl&quot;.</p><p><strong>Complexity:</strong> Time O(N × L); auxiliary space O(1), excluding the returned substring.</p><h3>PHP</h3><p><strong>Approach:</strong> Optimal vertical scanning.</p><p><strong>Explanation:</strong> PHP strings can be accessed by character position using square brackets for the lowercase English letters in this problem. We check that the position exists before comparing it. When a mismatch occurs, substr() returns the matching beginning portion.</p><p><strong>Complete PHP code</strong>Copy code</p><pre>&lt;?php<br>class Solution {<br>    function longestCommonPrefix($strs) {<br>      // If the list is empty, return an empty string.<br>        if (empty($strs)) {<br>            return &quot;&quot;;<br>        }<br>        // Select the first word as the reference word.<br>        $firstWord = $strs[0];<br>        // Check each character position in the reference word.<br>        for ($position = 0; $position &lt; strlen($firstWord); $position++) {<br>            // This is the character every word should have at this position.<br>            $expectedCharacter = $firstWord[$position];<br>            // Compare the same position in each word.<br>            foreach ($strs as $word) {<br>                // If the word has ended, the common prefix ends here.<br>                if ($position &gt;= strlen($word)) {<br>                    return substr($firstWord, 0, $position);<br>                }<br>                // If this character is different, return the prefix so far.<br>                if ($word[$position] !== $expectedCharacter) {<br>                    return substr($firstWord, 0, $position);<br>                }<br>            }<br>        }<br>        // No mismatch occurred, so the complete first word is common.<br>        return $firstWord;<br>    }<br>}<br>// Example:<br>// $solution = new Solution();<br>// echo $solution-&gt;longestCommonPrefix([&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;]);<br>// Output: fl<br>?&gt;</pre><p><strong>Example execution:</strong> Input: [&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;] → Output: &quot;fl&quot;.</p><p><strong>Complexity:</strong> Time O(N × L); auxiliary space O(1), excluding the returned substring. The problem restricts input to lowercase English letters, so PHP byte-based string indexing is suitable here.</p><h3>11. Time and Space Complexity Analysis</h3><p>Let N be the number of strings and L be the length of the shortest string. The algorithm cannot need to inspect more than L positions, because a common prefix cannot be longer than the shortest word.</p><p>ApproachTime complexityAuxiliary spaceReasonBrute force: test each prefixO(N × L²) upper boundO(L) depending on substring copiesThere can be L candidate prefixes, and checking each can inspect up to L characters in each of N strings.Optimal: vertical scanningO(N × L)O(1)At most L positions are checked across N strings, with no growing auxiliary data structure.</p><h3>Best, average and worst cases</h3><ul><li><strong>Best case:</strong> The first character differs in at least one string. Only the first position needs to be checked, so the work is proportional to the number of strings: O(N).</li><li><strong>Average case:</strong> The number of positions checked depends on where the first mismatch occurs. If it occurs after K matching positions, the work is at most proportional to N × (K + 1).</li><li><strong>Worst case:</strong> All strings match for the entire length of the shortest string. The algorithm checks up to N × L characters.</li></ul><p><strong>Space note:</strong> Auxiliary space describes temporary working memory and does not count the answer returned by the function. Some languages may allocate memory for the returned substring.</p><h3>12. Edge Cases</h3><p>InputExpected outputWhy?[&quot;flower&quot;, &quot;flow&quot;, &quot;flight&quot;]&quot;fl&quot;The first two positions match in every word.[&quot;dog&quot;, &quot;racecar&quot;, &quot;car&quot;]&quot;&quot;The first characters are different.[&quot;alone&quot;]&quot;alone&quot;With one word, the whole word is its own longest common prefix.[&quot;&quot;, &quot;abc&quot;]&quot;&quot;An empty string has no starting characters to share.[&quot;same&quot;, &quot;same&quot;, &quot;same&quot;]&quot;same&quot;All strings are identical.[&quot;ab&quot;, &quot;a&quot;]&quot;a&quot;The shorter string limits the prefix length.[&quot;a&quot;, &quot;b&quot;]&quot;&quot;The first position already differs.[&quot;prefix&quot;, &quot;pre&quot;, &quot;prevent&quot;]&quot;pre&quot;The shortest word ends after the shared letters.</p><h3>13. Common Mistakes</h3><ul><li><strong>Comparing letters anywhere in the words:</strong> A common prefix must begin at index zero. Do not search for matching letters in the middle.</li><li><strong>Continuing after a mismatch:</strong> Once one character position differs, no longer prefix can be valid. Return immediately.</li><li><strong>Ignoring shorter strings:</strong> A word may end before the reference word. Check its length before reading the character.</li><li><strong>Returning the shortest word automatically:</strong> The shortest word is only an upper limit. It may not match the beginning of the other words.</li><li><strong>Confusing prefix with substring:</strong> A substring can appear anywhere; a prefix must start at the beginning.</li><li><strong>Off-by-one errors:</strong> The mismatch position itself must not be included. That is why we return characters from index zero up to, but not including, the current position.</li><li><strong>Using unsafe indexing in Java:</strong> Check position &lt; word.length() before calling charAt(position).</li></ul><h3>14. Interview Preparation</h3><h3>Why do interviewers ask this?</h3><p>This is a compact way to test whether you understand strings, arrays, indexing, nested loops, early stopping and complexity analysis. It also reveals whether you handle shorter strings and mismatches safely.</p><h3>How to explain the optimal solution in an interview</h3><p>“I will scan the strings vertically, one character position at a time. I will use the first string as a reference and compare its character at the current position with the same position in every other string. If a string ends or any character differs, I will return the reference string before that position. If I finish the reference string without finding a mismatch, the entire reference string is the answer. The time complexity is O(N × L), and the auxiliary space is O(1).”</p><h3>Possible follow-up questions</h3><ul><li>How would you solve this if the strings arrive one at a time as a stream?</li><li>How would you handle uppercase letters, punctuation or Unicode characters?</li><li>Can you solve the problem by sorting the strings first?</li><li>What changes if the array contains millions of strings?</li><li>How would you find the longest common suffix instead of prefix?</li></ul><h3>Related variations to practise</h3><ul><li>Longest Common Substring</li><li>Longest Common Subsequence</li><li>Implement Trie (Prefix Tree)</li><li>Search Suggestions System</li></ul><h3>15. Frequently Asked Questions</h3><h3>1. What is a common prefix?</h3><p>It is a sequence of characters that appears at the beginning of every string in the list.</p><h3>2. What should we return if no prefix exists?</h3><p>Return an empty string: &quot;&quot;.</p><h3>3. Why do we use the first string as the reference?</h3><p>It gives us a convenient sequence of positions to inspect. Any common prefix must also be a prefix of this first string.</p><h3>4. Why do we stop at the first mismatch?</h3><p>A prefix cannot skip a character. If one position does not match, no longer starting sequence can match all strings.</p><h3>5. Can the answer be the entire first string?</h3><p>Yes. If every other string begins with the complete first string, then the first string is the longest common prefix.</p><h3>6. What is the optimal time complexity?</h3><p>O(N × L) in the worst case, where N is the number of strings and L is the length of the shortest string.</p><h3>7. Does the order of strings change the answer?</h3><p>No. The common prefix is the same regardless of order. We use the first string only as a convenient reference.</p><h3>16. Conclusion</h3><p>The Longest Common Prefix problem asks us to find the longest sequence of starting characters shared by every string. The key observation is that we only need to compare characters at the same position. As soon as a mismatch occurs or a string ends, the answer is known.</p><p>The vertical scanning approach is simple, efficient and easy to explain in an interview. It takes <strong>O(N × L)</strong> time in the worst case and uses <strong>O(1)</strong> auxiliary space, excluding the returned answer.</p><p><strong>Key takeaway:</strong> Compare from left to right, check every string at the same position, and stop at the first mismatch.</p><p>Practise this pattern with other string problems to become more confident with arrays, indexing and character comparisons. If this tutorial helped you, share it with a friend who is learning DSA and leave a comment with the next problem you would like explained.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b11091c7a6bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ENATS day 4 highlights]]></title>
            <link>https://medium.com/@studylearnandfun/enats-day-4-highlights-b7527cbd7bb3?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7527cbd7bb3</guid>
            <category><![CDATA[opencart]]></category>
            <category><![CDATA[todays-task]]></category>
            <category><![CDATA[day-4]]></category>
            <category><![CDATA[day-highlight]]></category>
            <category><![CDATA[open-cart-solutions]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 18:25:38 GMT</pubDate>
            <atom:updated>2025-06-19T18:25:38.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>👋 Hello everyone, welcome back!</h3><h3>🗓️ Day 4 at ENATS</h3><p><strong>Date:</strong> Thursday, June 19, 2025</p><h3>📌 Morning Arrival &amp; Task Overview</h3><p>I arrived at <strong>9:30 AM</strong> and began working on <strong>OpenCart</strong> — an open-source e-commerce platform. It’s equipped with built-in modules, making setup and configuration quite straightforward for online storefronts.</p><h3>⚙️ OpenCart 4.0.3 Setup</h3><p>My first mission was to fully install and configure OpenCart 4.0.3. I reviewed the official documentation and got hands-on guidance from colleagues. Here’s the step-by-step process:</p><ol><li><strong>Download</strong> OpenCart 4.0.3 ZIP and extract it.</li><li><strong>Copy</strong> the upload folder into htdocs, renaming it opencart.</li><li><strong>Create</strong> a new database via localhost/phpMyAdmin.</li><li><strong>Navigate</strong> to localhost/opencart in the browser:</li></ol><ul><li>Follow the installer prompts.</li><li>Address permission issues by creating/moving folders, deleting unnecessary files, and renaming config files as instructed.</li></ul><ol><li>Once completed, the admin dashboard and storefront went live without errors.</li></ol><h3>🏷️ Adding manufacturer_code Field</h3><p>My next task: add a new custom field — <strong>manufacturer_code</strong>—to the Manufacturers admin list.</p><p><strong>Steps undertaken:</strong></p><ul><li>Modified the database schema to include the new column in the manufacturers table.</li><li>Updated the manufacturer form:</li><li>Added manufacturer_code input in the add/edit form template.</li><li>Ensured it’s displayed and saved correctly.</li><li>Refreshed the admin list to show the new column.</li><li>Performed thorough testing to verify insertion, editing, display, and saving of the new field.</li></ul><p>I wrapped everything up by day’s end — database, forms, controller, and admin listing are all fully integrated and functional.</p><h3>📝 Summary of Achievements</h3><ul><li>✅ OpenCart 4.0.3 successfully installed and configured.</li><li>✅ Created and assigned a database, resolved file permissions.</li><li>✅ Added manufacturer_code field across database, admin form, controller, and list display.</li><li>✅ Completed testing — form, save, display, and update all working smoothly.</li></ul><h3>💬 Reflection &amp; Next Steps</h3><p>Today’s focus on platform setup and schema extension taught me a lot about:</p><ul><li>Handling file and config adjustments during E Commerce setups.</li><li>Extending OpenCart’s core components to add custom data fields.</li><li>Ensuring end-to-end functionality from database to admin UI.</li></ul><p>Tomorrow, I plan to build out front-end integration for the new field, making it visible in product listings and storefront filters.</p><h3>🔍 Want to Know More?</h3><p>Curious about how I adjusted the database schema, modified the Twig admin template, or updated the controller logic?<br> Comment below and I’d be happy to share the code snippets and techniques I used!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7527cbd7bb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello everyone and welcome! ]]></title>
            <link>https://medium.com/@studylearnandfun/hello-everyone-and-welcome-29993291447e?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/29993291447e</guid>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 18:33:06 GMT</pubDate>
            <atom:updated>2025-06-18T18:33:06.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*gM_MFC4RIdm151Cu" /></figure><p><strong>Hello everyone and welcome!</strong> 👋</p><p>Here’s a detailed and organized update on my third day at <strong>ENATS</strong>, building out API endpoints with token-based authentication 🚀</p><h3>🗓️ Day 3 at ENATS</h3><p><strong>Date:</strong> Wednesday, June 18, 2025</p><h3>Morning Sessions</h3><ul><li>Arrived at <strong>9:30 AM</strong> and carried forward the API work from yesterday.</li><li>Focused on <strong>authentication routes</strong> located in routes/api.php.</li><li>Thoroughly tested routes both <strong>with and without a token</strong>, ensuring correct responses</li><li>All authentication logic resides in my AuthController.</li></ul><h3>🔄 CRUD API Routes Implemented</h3><p>Following successful authentication testing, I created several essential endpoints:</p><p>Endpoint Method Functionality /post GET Fetch all blog posts of an authenticated user /post POST Create a new post (authentication required) /post/{id} GET Retrieve a specific post /post/update/{id} PUT Update a specific post /post/{id} DELETE Delete a specific post</p><h3>Afternoon: Testing &amp; Fixes</h3><ul><li>Rigorous testing on each route using Postman</li><li>Encountered several issues during method implementation.</li><li>Debugged and resolved routing bugs and controller logic mishaps.</li><li>Made updates to internal controller files and API Resource handling.</li></ul><h3>🌙 Evening Wrap-Up</h3><ul><li>Successfully built and tested the full authentication system.</li><li>All CRUD operations for Post are functional and secured.</li><li>Finalized the first version of the API; ready to build more features tomorrow.</li></ul><h3>📌 Key Takeaways &amp; Resources</h3><ol><li><strong>Laravel Sanctum</strong> provides a lightweight method for token-based API authentication. The typical flow:</li></ol><ul><li>Install Sanctum, publish config, migrate.</li><li>Add HasApiTokens to the User model.</li><li>Use auth:sanctum middleware to protect routes.</li></ul><ol><li>Protecting routes:</li></ol><h3>e Anything</h3><p>Curious about how I approached authentication, token validation, or debugging?<br> Drop your questions below — I’d love to dive deeper into any part of the setup!</p><p>I appreciate your support and interest! Let’s keep building 💪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29993291447e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Trial Day at a ENATS:]]></title>
            <link>https://medium.com/@studylearnandfun/my-first-trial-day-at-a-enats-1af63226820b?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1af63226820b</guid>
            <category><![CDATA[my-first-day]]></category>
            <category><![CDATA[what-have-i-done]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[work-at-office]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 17:58:36 GMT</pubDate>
            <atom:updated>2025-06-16T17:58:36.223Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends,</p><p>Today, I embarked on my first trial day at a small firm with a team of 10. After a successful interview, I was eager to dive into real-world development tasks. Here’s a detailed account of my day:</p><p><strong>Morning Session: Implementing Pagination in a CRUD Application</strong></p><p>My day began at 9:30 AM amidst heavy rainfall. Upon arrival, I observed the team working diligently. After a brief period, I approached my supervisor to inquire about my tasks. He assigned me the responsibility of adding pagination to an existing CRUD application — a project I had worked on during the interview.</p><p>To efficiently manage a large dataset, I utilized Laravel’s seeder functionality to generate fake data. This allowed me to populate the database with sufficient records for testing pagination.</p><p>For pagination, I employed Laravel’s paginate() method to limit the number of records displayed per page. To enhance the user interface, I integrated Bootstrap 5 pagination by calling the links() method in the view, ensuring a seamless and responsive pagination experience.</p><p><strong>Code Snippet:</strong></p><pre>// In Controller<br>$posts = Post::paginate(10);<br>// In Blade View<br>{{ $posts-&gt;links(&#39;pagination::bootstrap-5&#39;) }}</pre><p><strong>Afternoon Session: Diving into API Development</strong></p><p>Post-lunch, I was tasked with learning about API development — a domain I was unfamiliar with. I dedicated the remainder of the day to studying Laravel’s documentation and exploring ChatGPT for guidance.</p><p>In Laravel 12, the api.php route file isn&#39;t included by default. To set up API routes, I manually created the routes/api.php file and registered it in bootstrap/app.php.</p><p><strong>Steps to Set Up API Routes:</strong></p><ol><li><strong>Create the </strong><strong>api.php File:</strong></li></ol><pre>php artisan make:controller Api/PostController</pre><p><strong>2. Define API Routes:</strong></p><pre>// In routes/api.php use App\Http\Controllers\Api\PostController; <br>Route::apiResource(&#39;posts&#39;, PostController::class);</pre><p><strong>3. Register the </strong><strong>api.php File:</strong></p><pre>// In bootstrap/app.php <br>$app-&gt;withRouting(<br>     web: __DIR__.&#39;/../routes/web.php&#39;,<br>     api: __DIR__.&#39;/../routes/api.php&#39;,<br>     commands: __DIR__.&#39;/../routes/console.php&#39;, );</pre><ol><li><strong>Create Model, Migration, and Controller:</strong></li></ol><pre>php artisan make:model Post -mcr</pre><ol><li><strong>Update Migration File:</strong></li></ol><pre>public function up() {<br>     Schema::create(&#39;posts&#39;, function (Blueprint $table) <br>{<br>         $table-&gt;id();<br>         $table-&gt;string(&#39;title&#39;);<br>         $table-&gt;text(&#39;body&#39;);<br>         $table-&gt;timestamps();<br>     });<br> }</pre><ol><li><strong>Define Controller Methods:</strong></li></ol><pre>public function index() {<br>     return Post::all();<br> }<br>  public function store(Request $request) {<br>     $data = $request-&gt;validate([<br>         &#39;title&#39; =&gt; &#39;required|string&#39;,<br>         &#39;body&#39; =&gt; &#39;required|string&#39;,<br>     ]);<br>     return Post::create($data);<br> }</pre><p>By the end of the day, I had successfully set up basic API routes and operations. The next step involves implementing token-based authentication, which I plan to tackle in the coming days.</p><p><strong>Conclusion:</strong></p><p>My first trial day was both challenging and rewarding. I gained hands-on experience with Laravel’s pagination system and initiated my journey into API development. I’m excited about the learning opportunities ahead and look forward to contributing more to the team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1af63226820b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Pass Data from One URL to Another in Laravel]]></title>
            <link>https://medium.com/@studylearnandfun/how-to-pass-data-from-one-url-to-another-in-laravel-295c270e3038?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/295c270e3038</guid>
            <category><![CDATA[laravel-12]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[passing-data-in-laravel]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Sat, 31 May 2025 19:27:01 GMT</pubDate>
            <atom:updated>2025-06-01T15:09:51.088Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“How do I pass data from one page (URL) to another?”</blockquote><p>Whether it’s a form submission, a dynamic link, or redirecting with values — Laravel makes it super simple. In this post, I’ll walk you through <strong>how to pass data via URL in Laravel</strong>, <strong>how to retrieve it</strong>, and <strong>where to write the code</strong>. 🙌</p><h3>🧠 What You’ll Learn</h3><ul><li>How to create routes that pass data</li><li>How to send data via URL (GET)</li><li>How to retrieve that data in a controller or view</li><li>Real-world example with step-by-step code</li><li>What the output will look like</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*5AVg2ZqcmldUnR3q_LltkQ.png" /></figure><h3>🛠 Step 1: Set Up a Fresh Laravel Project (Optional)</h3><p>If you’re just testing this out:</p><pre>laravel new url-passing-demo<br>cd url-passing-demo<br>php artisan serve</pre><p>Or use an existing Laravel project.</p><h3>📁 Step 2: Create Two Routes in web.php</h3><p>Let’s say we want to go from:</p><ul><li>Page 1: <a href="http://localhost:8000/user/John/21">http://localhost:8000/user/John/21</a></li><li>To show: &quot;Hello John, your age is 21&quot;</li></ul><p>Open routes/web.php and add:</p><pre>use Illuminate\Support\Facades\Route;<br>Route::get(&#39;/user/{name}/{age}&#39;, function ($name, $age) {<br>    return view(&#39;user&#39;, [&#39;name&#39; =&gt; $name, &#39;age&#39; =&gt; $age]);<br>});</pre><p>✅ <strong>What’s happening here?</strong></p><ul><li>{name} and {age} are <strong>route parameters</strong>.</li><li>When you visit this URL → localhost:8000/user/John/21, it grabs:</li><li>$name = John</li><li>$age = 21</li><li>Then it sends them to the user.blade.php view.</li></ul><h3>🧾 Step 3: Create a View File (resources/views/user.blade.php)</h3><p>Now let’s display that data:</p><pre>&lt;!-- resources/views/user.blade.php --&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;User Info&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Hello {{ $name }}, your age is {{ $age }}!&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>✅ Output when you visit <a href="http://localhost:8000/user/John/21:">http://localhost:8000/user/John/21:</a></h3><pre>Hello John, your age is 21!</pre><p>💡 You can change the name and age directly in the URL:<br> /user/Aisha/30 → &quot;Hello Aisha, your age is 30!&quot;</p><h3>🧭 Step 4: Link to Another URL with Data</h3><p>Let’s say you’re on a home page and want to <strong>redirect to a user page with data</strong>.</p><p>In web.php:</p><pre>Route::get(&#39;/&#39;, function () {<br>    $name = &quot;Rahul&quot;;<br>    $age = 25;<br>    return redirect()-&gt;route(&#39;user.info&#39;, [&#39;name&#39; =&gt; $name, &#39;age&#39; =&gt; $age]);<br>});<br>Route::get(&#39;/user/{name}/{age}&#39;, function ($name, $age) {<br>    return view(&#39;user&#39;, compact(&#39;name&#39;, &#39;age&#39;));<br>})-&gt;name(&#39;user.info&#39;);</pre><p>✅ Here, we’re:</p><ul><li>Defining a named route: user.info</li><li>Redirecting to that route with parameters name and age</li></ul><h3>🎯 Bonus: Passing Data Using Query String (e.g., ?name=John&amp;age=22)</h3><p>In web.php:</p><pre>Route::get(&#39;/show&#39;, function (Illuminate\Http\Request $request) {<br>    $name = $request-&gt;query(&#39;name&#39;);<br>    $age = $request-&gt;query(&#39;age&#39;);<br>    return &quot;Hi $name, you are $age years old!&quot;;<br>});</pre><p>Now visit:<br> ➡️ http://localhost:8000/show?name=Ravi&amp;age=22<br> 📋 Output:</p><pre>Hi Ravi, you are 22 years old!</pre><h3>🎁 Real-Life Use Case</h3><p>Imagine you’re on a user list page, and when you click on a user, you want to go to a details page:</p><pre>&lt;!-- user-list.blade.php --&gt;<br>@foreach($users as $user)<br>    &lt;a href=&quot;{{ url(https://medium.com/&#39;/user/&#39;.$user-&gt;name.&#39;/&#39;.$user-&gt;age) }}&quot;&gt;<br>        {{ $user-&gt;name }}<br>    &lt;/a&gt;&lt;br&gt;<br>@endforeach</pre><p>Clicking that will take you to:<br> /user/John/23 → and show &quot;Hello John, your age is 23!&quot;</p><h3>✅ Final Thoughts</h3><p>Laravel makes it easy to pass data through routes using:</p><ul><li>Route Parameters (clean and RESTful)</li><li>Query Strings (for optional values or filters)</li><li>Redirects and Named Routes (for structured control)</li></ul><p>Once you get the hang of this, you’ll start building <strong>dynamic pages</strong>, <strong>profile views</strong>, <strong>product details</strong>, and much more in no time. 💪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=295c270e3038" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Roman to Integer — Mastering a Classic Coding Problem]]></title>
            <link>https://medium.com/@studylearnandfun/%EF%B8%8F-roman-to-integer-mastering-a-classic-coding-problem-b340f0c9272f?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b340f0c9272f</guid>
            <category><![CDATA[roman-to-integer]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[problem-13]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Fri, 30 May 2025 18:32:32 GMT</pubDate>
            <atom:updated>2025-05-30T18:32:32.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>🏛️ Roman to Integer — Mastering a Classic Coding Problem</h3><p><strong>Difficulty</strong>: Easy<br> <strong>LeetCode Problem #13</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*NHc7DZFH9eGtY5Nrdw85Fw.png" /></figure><p>Whether you’re prepping for coding interviews or brushing up your algorithm skills, <strong>converting Roman numerals to integers</strong> is a classic problem worth mastering. Let’s walk through the logic, break it down step-by-step, and solve it using <strong>PHP</strong>, <strong>Python</strong>, <strong>Java</strong>, and <strong>JavaScript</strong>.</p><h3>📜 What Are Roman Numerals?</h3><p>Roman numerals are made up of seven symbols:</p><p>Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000</p><p>Generally, symbols are placed from <strong>largest to smallest</strong> from left to right. But there are <strong>six special subtraction cases</strong>:</p><ul><li><strong>I</strong> before <strong>V</strong> or <strong>X</strong> → 4 (IV), 9 (IX)</li><li><strong>X</strong> before <strong>L</strong> or <strong>C</strong> → 40 (XL), 90 (XC)</li><li><strong>C</strong> before <strong>D</strong> or <strong>M</strong> → 400 (CD), 900 (CM)</li></ul><h3>🧠 Problem Statement</h3><blockquote><em>Given a Roman numeral as a string, convert it to an integer.</em></blockquote><h3>🔍 Strategy</h3><ol><li>Create a mapping of Roman symbols to their values.</li><li>Loop through the string:</li></ol><ul><li>Compare current symbol with the next one.</li><li>If current &gt;= next → <strong>add it</strong>.</li><li>If current &lt; next → <strong>subtract it</strong>.</li></ul><ol><li>Sum everything and return the result.</li></ol><h3>🔎 Example: &quot;MCMXCIV&quot;</h3><pre>M(1000) + CM(900) + XC(90) + IV(4) = 1994</pre><h3>🧑‍💻 PHP Code</h3><pre>class Solution {<br>    function romanToInt($s) {<br>        $roman = [<br>            &#39;I&#39;=&gt; 1, &#39;V&#39;=&gt; 5, &#39;X&#39;=&gt;10,<br>            &#39;L&#39;=&gt;50, &#39;C&#39;=&gt;100, &#39;D&#39;=&gt;500, &#39;M&#39;=&gt;1000<br>        ];<br>        $length = strlen($s);<br>        $total = 0;<br>        for ($i = 0; $i &lt; $length; $i++) {<br>            $current = $roman[$s[$i]];<br>            $next = $roman[$s[$i + 1]] ?? 0;<br>            if ($current &gt;= $next) {<br>                $total += $current;<br>            } else {<br>                $total -= $current;<br>            }<br>        }<br>        return $total;<br>    }<br>}</pre><h3>🐍 Python Code</h3><pre>class Solution:<br>    def romanToInt(self, s: str) -&gt; int:<br>        roman = {<br>            &#39;I&#39;: 1, &#39;V&#39;: 5, &#39;X&#39;: 10,<br>            &#39;L&#39;: 50, &#39;C&#39;: 100, &#39;D&#39;: 500, &#39;M&#39;: 1000<br>        }<br>        total = 0<br>        for i in range(len(s)):<br>            current = roman[s[i]]<br>            next_val = roman[s[i + 1]] if i + 1 &lt; len(s) else 0<br>            if current &gt;= next_val:<br>                total += current<br>            else:<br>                total -= current<br>        return total</pre><h3>☕ Java Code</h3><pre>class Solution {<br>    public int romanToInt(String s) {<br>        Map&lt;Character, Integer&gt; roman = Map.of(<br>            &#39;I&#39;, 1, &#39;V&#39;, 5, &#39;X&#39;, 10,<br>            &#39;L&#39;, 50, &#39;C&#39;, 100, &#39;D&#39;, 500, &#39;M&#39;, 1000<br>        );<br>        int total = 0;<br>        for (int i = 0; i &lt; s.length(); i++) {<br>            int current = roman.get(s.charAt(i));<br>            int next = (i + 1 &lt; s.length()) ? roman.get(s.charAt(i + 1)) : 0;<br>            if (current &gt;= next) {<br>                total += current;<br>            } else {<br>                total -= current;<br>            }<br>        }<br>        return total;<br>    }<br>}</pre><h3>🌐 JavaScript Code</h3><pre>var romanToInt = function(s) {<br>    const roman = {<br>        &#39;I&#39;: 1, &#39;V&#39;: 5, &#39;X&#39;: 10,<br>        &#39;L&#39;: 50, &#39;C&#39;: 100, &#39;D&#39;: 500, &#39;M&#39;: 1000<br>    };<br>    let total = 0;<br>    for (let i = 0; i &lt; s.length; i++) {<br>        let current = roman[s[i]];<br>        let next = roman[s[i + 1]] || 0;<br>        if (current &gt;= next) {<br>            total += current;<br>        } else {<br>            total -= current;<br>        }<br>    }<br>    return total;<br>};</pre><h3>📈 Complexity</h3><ul><li><strong>Time</strong>: O(n), where n is the length of the string</li><li><strong>Space</strong>: O(1), constant space for the map</li></ul><h3>🎯 Final Thoughts</h3><p>The <strong>Roman to Integer</strong> problem is not just a string parsing exercise — it teaches you:</p><ul><li>The power of hash maps</li><li>Simple greedy algorithms</li><li>Conditional logic in iterative loops</li></ul><p>Understanding this will make future parsing or conversion problems easier to grasp. Add it to your toolkit of <strong>interview essentials</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b340f0c9272f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running your first laravel project]]></title>
            <link>https://medium.com/@studylearnandfun/running-your-first-laravel-project-8eae3170237c?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eae3170237c</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Fri, 30 May 2025 16:04:07 GMT</pubDate>
            <atom:updated>2025-05-30T16:04:07.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ncDn_Gl2w4d4tfim.png" /></figure><h3>🛠️ How to Create &amp; Run Your First Laravel Project (Step-by-Step Guide)</h3><h3>✅ Step 1: Install Laravel</h3><blockquote><em>⚠️ You must have </em><strong><em>Composer</em></strong><em> and </em><strong><em>PHP (8.1 or higher)</em></strong><em> already installed.</em></blockquote><p>If not installed:</p><ul><li>Composer: <a href="https://getcomposer.org/">https://getcomposer.org/</a></li><li>PHP: <a href="https://windows.php.net/download">https://windows.php.net/download</a></li></ul><p>You can check using:</p><pre>php -v<br>composer -v</pre><h3>✅ Step 2: Create Your First Project</h3><p>Open <strong>Command Prompt</strong> or <strong>Terminal</strong>, then run:</p><pre>laravel new my-app</pre><ul><li>my-app is your project name. You can use any name, e.g., laravel-blog, my-store, etc.</li><li>This command downloads Laravel and sets up the whole folder structure.</li></ul><p>If laravel command doesn’t work, install Laravel globally:</p><pre>composer global require laravel/installer<br>or<br>composer create-project --prefer-dist laravel/laravel project-name</pre><blockquote><em>🔄 It might ask for:</em></blockquote><ul><li><strong>Database</strong>: choose MySQL</li><li><strong>Testing</strong>: choose Pest or PHPUnit</li><li><strong>Frontend stack</strong>: pick whatever is recommended or skip for now</li></ul><h3>✅ Step 3: Open Project in VS Code</h3><p>Go to the folder:</p><pre>cd my-app</pre><p>Now open it in <strong>VS Code</strong>: The below command will open your current project in VS code</p><pre>code .</pre><h3>✅ Step 4: Run the Project</h3><p>In the VS Code open terminal or any command prompt, run:</p><pre>php artisan serve</pre><blockquote><em>✅ This will start a development server at:</em></blockquote><pre>http://127.0.0.1:8000</pre><p>Open that URL in your browser. You will see the Laravel <strong>welcome page</strong>.</p><h3>✅ Step 5: How is the Welcome Page Working?</h3><p>Here’s how Laravel connects everything:</p><h4>🧩 routes/web.php</h4><p>This file contains route definitions.</p><p>Default route looks like:</p><pre>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});</pre><ul><li>/ means homepage.</li><li>It means that whenever you write “/” in your url and enter it will return you the page mentioned in this view(‘welcome’).</li><li>It returns the view called welcome.</li></ul><h4>🧩 resources/views/welcome.blade.php</h4><p>This is the HTML file you see in the browser. You can edit this file and refresh the browser to see changes.</p><h3>🧪 Example:</h3><p>Let’s say you want to make a new page called about.</p><ol><li>Create a new file: resources/views/about.blade.php</li></ol><pre>&lt;!DOCTYPE html&gt;<br> &lt;html&gt;<br> &lt;head&gt;<br>&lt;title&gt;About Page&lt;/title&gt;<br>&lt;/head&gt; <br>&lt;body&gt; <br>    &lt;h1&gt;About Laravel Project&lt;/h1&gt;<br> &lt;/body&gt;<br> &lt;/html&gt;</pre><ol><li>Add this in web.php:</li></ol><pre>Route::get(&#39;/about&#39;, function () {<br>    return view(&#39;about&#39;);<br>});</pre><ol><li>Now open your browser and visit:<br>👉 <a href="http://127.0.0.1:8000/about">http://127.0.0.1:8000/about</a></li></ol><p>You’ll see your new page!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eae3170237c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to LeetCode’s Palindrome Problem]]></title>
            <link>https://medium.com/@studylearnandfun/step-by-step-guide-to-leetcodes-palindrome-problem-f75ce880c73a?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f75ce880c73a</guid>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-question]]></category>
            <category><![CDATA[pallindrome-problem]]></category>
            <category><![CDATA[problem-no-9]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Thu, 29 May 2025 16:06:20 GMT</pubDate>
            <atom:updated>2025-05-29T16:06:20.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*cNttb2xgqoVe2eeX.png" /></figure><h3>LeetCode’s Palindrome Number Problem</h3><p>Ever wondered if a number reads the same forwards and backward? That’s the essence of a palindrome! Today, we’re going to tackle a classic coding challenge that popped up on our screen: LeetCode’s “9. Palindrome Number.”</p><h3>What’s the Problem All About?</h3><p>The challenge is straightforward: given an integer x, determine if it&#39;s a palindrome.</p><ul><li><strong>Example 1:</strong> x = 121</li><li>Reads 121 from left to right.</li><li>Reads 121 from right to left.</li><li><strong>Output:</strong> true (It&#39;s a palindrome!)</li><li><strong>Example 2:</strong> x = -121</li><li>Reads -121 from left to right.</li><li>Reads 121- from right to left.</li><li><strong>Output:</strong> false (Not a palindrome, because of the negative sign!)</li><li><strong>Example 3:</strong> x = 10</li><li>Reads 10 from left to right.</li><li>Reads 01 from right to left.</li><li><strong>Output:</strong> false (Not a palindrome!)</li></ul><h3>The Simple Approach (and Why It’s Often a Good Start!)</h3><p>The most intuitive way to solve this problem is to convert the number into a string and then check if the string is the same when reversed.</p><p>Let’s break down the logic:</p><ol><li><strong>Handle Negative Numbers:</strong> Any negative number cannot be a palindrome. Why? Because the negative sign breaks the symmetry. -121 becomes 121- when reversed. So, if x is less than 0, we immediately return false.</li><li><strong>Convert to String:</strong> Transform the integer into its string representation. This makes it easy to reverse.</li><li><strong>Reverse the String:</strong> Reverse the newly created string.</li><li><strong>Compare:</strong> Compare the original string with the reversed string. If they are identical, then the number is a palindrome!</li></ol><h3>Optimized Code (with Comments!)</h3><p>While the string conversion method is easy to understand, we can often do better, especially in interviews. A more optimized approach involves reversing half of the number without converting it to a string, avoiding extra memory allocation.</p><h4>PHP</h4><pre>&lt;?php<br>class Solution {<br>    /**<br>     * @param Integer $x<br>     * @return Boolean<br>     */<br>    function isPalindrome($x) {<br>        // Step 1: Handle negative numbers. Negative numbers cannot be palindromes.<br>        if ($x &lt; 0) {<br>            return false;<br>        }<br>        // Step 2: Convert the integer to a string.<br>        $original = strval($x);<br>        // Step 3: Reverse the string.<br>        $reversed = strrev($original);<br>        // Step 4: Compare the original and reversed strings.<br>        return $original === $reversed;<br>    }<br>}<br>// --- Optimized PHP Solution (without string conversion for numbers) ---<br>class OptimizedSolution {<br>    /**<br>     * @param Integer $x<br>     * @return Boolean<br>     */<br>    function isPalindrome($x) {<br>        // Edge cases:<br>        // 1. Negative numbers are not palindromes.<br>        // 2. Numbers ending in 0 (except 0 itself) cannot be palindromes<br>        //    because the reversed number would start with 0.<br>        if ($x &lt; 0 || ($x % 10 == 0 &amp;&amp; $x != 0)) {<br>            return false;<br>        }<br>        $revertedNumber = 0;<br>        // Keep looping as long as the original number is greater than the reverted number.<br>        // This effectively reverses only half of the number.<br>        while ($x &gt; $revertedNumber) {<br>            // Get the last digit of x and append it to revertedNumber.<br>            $revertedNumber = $revertedNumber * 10 + ($x % 10);<br>            // Remove the last digit from x.<br>            $x = (int)($x / 10); // Use (int) for integer division<br>        }<br>        // When the length of the number is odd, the middle digit will be in the original x,<br>        // so we divide revertedNumber by 10 to remove the last digit (which is the middle digit).<br>        // If the length is even, x and revertedNumber will be equal.<br>        return $x == $revertedNumber || $x == (int)($revertedNumber / 10);<br>    }<br>}<br>?&gt;</pre><h4>Java</h4><pre>class Solution {<br>    public boolean isPalindrome(int x) {<br>        // Step 1: Handle negative numbers. Negative numbers cannot be palindromes.<br>        if (x &lt; 0) {<br>            return false;<br>        }<br>// Step 2: Convert the integer to a string.<br>        String original = String.valueOf(x);<br>        // Step 3: Reverse the string.<br>        StringBuilder reversed = new StringBuilder(original).reverse();<br>        // Step 4: Compare the original and reversed strings.<br>        return original.equals(reversed.toString());<br>    }<br>}<br>// --- Optimized Java Solution (without string conversion) ---<br>class OptimizedSolutionJava {<br>    public boolean isPalindrome(int x) {<br>        // Edge cases:<br>        // 1. Negative numbers are not palindromes.<br>        // 2. Numbers ending in 0 (except 0 itself) cannot be palindromes<br>        //    because the reversed number would start with 0.<br>        if (x &lt; 0 || (x % 10 == 0 &amp;&amp; x != 0)) {<br>            return false;<br>        }<br>        int revertedNumber = 0;<br>        // Keep looping as long as the original number is greater than the reverted number.<br>        // This effectively reverses only half of the number.<br>        while (x &gt; revertedNumber) {<br>            // Get the last digit of x and append it to revertedNumber.<br>            revertedNumber = revertedNumber * 10 + x % 10;<br>            // Remove the last digit from x.<br>            x /= 10;<br>        }<br>        // When the length of the number is odd, the middle digit will be in the original x,<br>        // so we divide revertedNumber by 10 to remove the last digit (which is the middle digit).<br>        // If the length is even, x and revertedNumber will be equal.<br>        return x == revertedNumber || x == revertedNumber / 10;<br>    }<br>}</pre><h4>Python</h4><pre>class Solution:<br>    def isPalindrome(self, x: int) -&gt; bool:<br>        # Step 1: Handle negative numbers. Negative numbers cannot be palindromes.<br>        if x &lt; 0:<br>            return False<br># Step 2: Convert the integer to a string.<br>        original = str(x)<br>        # Step 3: Reverse the string. Python&#39;s slicing is very concise for this.<br>        reversed_str = original[::-1]<br>        # Step 4: Compare the original and reversed strings.<br>        return original == reversed_str<br># --- Optimized Python Solution (without string conversion) ---<br>class OptimizedSolutionPython:<br>    def isPalindrome(self, x: int) -&gt; bool:<br>        # Edge cases:<br>        # 1. Negative numbers are not palindromes.<br>        # 2. Numbers ending in 0 (except 0 itself) cannot be palindromes<br>        #    because the reversed number would start with 0.<br>        if x &lt; 0 or (x % 10 == 0 and x != 0):<br>            return False<br>        reverted_number = 0<br>        # Keep looping as long as the original number is greater than the reverted number.<br>        # This effectively reverses only half of the number.<br>        while x &gt; reverted_number:<br>            # Get the last digit of x and append it to reverted_number.<br>            reverted_number = reverted_number * 10 + x % 10<br>            # Remove the last digit from x (integer division).<br>            x //= 10<br>        # When the length of the number is odd, the middle digit will be in the original x,<br>        # so we divide reverted_number by 10 to remove the last digit (which is the middle digit).<br>        # If the length is even, x and reverted_number will be equal.<br>        return x == reverted_number or x == reverted_number // 10</pre><h4>JavaScript</h4><pre>/**<br> * @param {number} x<br> * @return {boolean}<br> */<br>var isPalindrome = function(x) {<br>    // Step 1: Handle negative numbers. Negative numbers cannot be palindromes.<br>    if (x &lt; 0) {<br>        return false;<br>    }<br>// Step 2: Convert the integer to a string.<br>    let original = String(x);<br>    // Step 3: Reverse the string.<br>    let reversed = original.split(&#39;&#39;).reverse().join(&#39;&#39;);<br>    // Step 4: Compare the original and reversed strings.<br>    return original === reversed;<br>};<br>// --- Optimized JavaScript Solution (without string conversion) ---<br>/**<br> * @param {number} x<br> * @return {boolean}<br> */<br>var isPalindromeOptimized = function(x) {<br>    // Edge cases:<br>    // 1. Negative numbers are not palindromes.<br>    // 2. Numbers ending in 0 (except 0 itself) cannot be palindromes<br>    //    because the reversed number would start with 0.<br>    if (x &lt; 0 || (x % 10 === 0 &amp;&amp; x !== 0)) {<br>        return false;<br>    }<br>    let revertedNumber = 0;<br>    // Keep looping as long as the original number is greater than the reverted number.<br>    // This effectively reverses only half of the number.<br>    while (x &gt; revertedNumber) {<br>        // Get the last digit of x and append it to revertedNumber.<br>        revertedNumber = revertedNumber * 10 + (x % 10);<br>        // Remove the last digit from x (integer division).<br>        x = Math.floor(x / 10);<br>    }<br>    // When the length of the number is odd, the middle digit will be in the original x,<br>    // so we divide revertedNumber by 10 to remove the last digit (which is the middle digit).<br>    // If the length is even, x and revertedNumber will be equal.<br>    return x === revertedNumber || x === Math.floor(revertedNumber / 10);<br>};</pre><h3>Explaining the Optimized Approach (The “Reverse Half” Method)</h3><p>The optimized solutions above avoid string conversions by playing with numbers directly. Here’s a breakdown:</p><ol><li><strong>Initial Checks:</strong></li></ol><ul><li>Just like before, negative numbers are out.</li><li>A new crucial check: if a number ends in 0 (like 120), and it&#39;s not 0 itself, it cannot be a palindrome. Why? Because its reverse would start with 0 (e.g., 021), which is not how numbers are typically represented. 0 itself <em>is</em> a palindrome.</li></ul><ol><li><strong>Reversing Half the Number:</strong></li></ol><ul><li>We use a while loop that continues as long as x (our original number) is greater than revertedNumber.</li><li>Inside the loop:</li><li>revertedNumber = revertedNumber * 10 + x % 10;: This line does two things:</li><li>x % 10 extracts the last digit of x.</li><li>revertedNumber * 10 shifts the existing revertedNumber one place to the left, making space for the new digit.</li><li>We then add the extracted last digit to revertedNumber.</li><li>x = (int)(x / 10); (or x //= 10 in Python, x /= 10 in Java/JS): This line removes the last digit from x, effectively &quot;shortening&quot; the original number.</li></ul><ol><li><strong>The Comparison:</strong></li></ol><ul><li>The loop stops when x becomes less than or equal to revertedNumber. At this point, we&#39;ve effectively reversed half of the original number.</li><li><strong>Case 1: Even Number of Digits:</strong> If the original number had an even number of digits (e.g., 1221), the loop will stop when x becomes equal to revertedNumber (e.g., x becomes 12, revertedNumber becomes 12). In this case, x == revertedNumber will be true.</li><li><strong>Case 2: Odd Number of Digits:</strong> If the original number had an odd number of digits (e.g., 12321), the loop will stop when x has one more digit than revertedNumber (e.g., x becomes 12, revertedNumber becomes 123). The middle digit is now in revertedNumber. To account for this, we check x == (int)(revertedNumber / 10). Dividing revertedNumber by 10 removes its last digit (the middle digit), allowing us to compare the remaining halves.</li></ul><p>This optimized approach is generally preferred as it avoids the overhead of string conversions and can be more efficient for very large numbers.</p><h3>Why Does This Matter?</h3><p>Understanding problems like “Palindrome Number” is crucial for several reasons:</p><ul><li><strong>Foundation of Algorithms:</strong> It teaches fundamental concepts like number manipulation, string operations, and conditional logic.</li><li><strong>Problem-Solving Skills:</strong> Breaking down a problem into smaller, manageable steps is a core skill for any programmer.</li><li><strong>Interview Preparation:</strong> These types of questions are common in technical interviews, assessing your analytical thinking and coding proficiency.</li><li><strong>Optimization:</strong> Learning to go beyond the most straightforward solution and think about efficiency is a valuable habit.</li></ul><p>So, the next time you encounter a number, take a moment to ponder: is it a palindrome? With these techniques, you’re well-equipped to find out! Happy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f75ce880c73a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Reverse Integer — LeetCode Problem #7 (Explained Simply)]]></title>
            <link>https://medium.com/@studylearnandfun/reverse-integer-leetcode-problem-7-explained-simply-a8aa2aba35d4?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8aa2aba35d4</guid>
            <category><![CDATA[leetcode-reverse-integer]]></category>
            <category><![CDATA[leetcode-solution]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-problem-7]]></category>
            <category><![CDATA[leetcode-problem]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Tue, 27 May 2025 18:36:15 GMT</pubDate>
            <atom:updated>2025-05-27T18:36:15.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌀 Reverse Integer — LeetCode Problem #7 (Explained Simply)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*pKOzkYaxDtqlW79Zqhr-fw.png" /></figure><p>One of the classic coding interview questions is the <strong>Reverse Integer</strong> problem. It’s a great problem to practice integer manipulation and boundary checking.</p><h3>🧩 Problem Statement</h3><blockquote><em>Given a signed 32-bit integer </em><em>x, return </em><em>x with its digits reversed.<br>If reversing </em><em>x causes the value to go outside the signed 32-bit integer range </em><em>[-2³¹, 2³¹ - 1], return </em><em>0.</em></blockquote><h3>✅ Examples</h3><ul><li><strong>Input</strong>: 123 → <strong>Output</strong>: 321</li><li><strong>Input</strong>: -123 → <strong>Output</strong>: -321</li><li><strong>Input</strong>: 120 → <strong>Output</strong>: 21</li></ul><h3>⚠️ Constraints</h3><p>A <strong>signed 32-bit integer</strong> means the number must lie within:</p><pre>-2,147,483,648 to 2,147,483,647</pre><p>If the reversed number exceeds this range, we return 0.</p><h3>👣 Step-by-Step Approach</h3><ol><li>Check if the number is <strong>negative</strong>.</li><li>Take the <strong>absolute value</strong> of the number and reverse the digits.</li><li>Convert the reversed string back to an integer.</li><li>If the reversed number exceeds the 32-bit signed range, return 0.</li><li>Otherwise, return the reversed number, keeping the sign correct.</li></ol><h3>🧪 Test Cases</h3><p>Input — — — — →Output</p><p>123 — — — — — —&gt;321</p><p>-123 — — — — — → -321</p><p>120 — — — — — → 12</p><p>1534236469 — → 0</p><h3>💡 PHP Solution</h3><pre>class Solution {<br>    function reverse($x) {<br>        // Check if the number is negative<br>        $isNegative = $x &lt; 0;<br>// Convert the number to positive and then to a string, reverse it<br>        $reverseNum = strrev(strval(abs($x)));<br>        // Convert the reversed string back to an integer<br>        $rev = (int)$reverseNum;<br>        // If the reversed number is more than 32-bit limit, return 0<br>        if ($rev &gt; 2147483647) {<br>            return 0;<br>        }<br>        // If original number was negative, return negative reversed number<br>        return $isNegative ? -$rev : $rev;<br>    }<br>}</pre><h3>✅ Explanation</h3><ul><li>abs($x) removes the negative sign.</li><li>strrev(strval(...)) reverses the number.</li><li>Type cast back to integer using (int).</li><li>Check overflow before returning.</li></ul><h3>🐍 Python Solution</h3><pre>def reverse(x):<br>    # Check if number is negative (less than 0)<br>    negative = x &lt; 0<br>    # Get the absolute value (e.g., -123 becomes 123)<br>    x = abs(x)<br>    # Convert number to string, reverse it, then turn it back into integer<br>    reversed_x = int(str(x)[::-1])<br>    # If reversed number is more than allowed 32-bit max value, return 0<br>    if reversed_x &gt; 2**31 - 1:<br>        return 0<br>    # Add the negative sign back if original number was negative<br>    return -reversed_x if negative else reversed_x</pre><h3>✅ Explanation</h3><ul><li>We reverse the number using Python slicing [::-1].</li><li>Overflow is handled by comparing with 2**31 - 1.</li></ul><h3>☕ Java Solution</h3><pre>public class Solution {<br>    public int reverse(int x) {<br>        // We&#39;ll use a long to safely store the reversed number<br>        long rev = 0;<br>        // Loop until x becomes 0<br>        while (x != 0) {<br>            // Get the last digit of x (e.g., 123 -&gt; 3)<br>            rev = rev * 10 + x % 10;<br>            // Remove the last digit from x (e.g., 123 -&gt; 12)<br>            x = x / 10;<br>        }<br>        // Check if reversed number is within 32-bit integer limits<br>        if (rev &gt; Integer.MAX_VALUE || rev &lt; Integer.MIN_VALUE) {<br>            return 0;<br>        }<br>        // Convert the long result back to int and return<br>        return (int) rev;<br>    }<br>}</pre><h3>✅ Explanation</h3><ul><li>Use modulo % 10 to get last digit.</li><li>Use division / 10 to remove last digit.</li><li>Use a long for overflow check during the loop.</li></ul><h3>🌐 JavaScript Solution</h3><pre>var reverse = function(x) {<br>    // Check if number is negative<br>    let isNegative = x &lt; 0;<br>    // Convert to positive, then to string, reverse it, and convert back to number<br>    let reversed = parseInt(Math.abs(x).toString().split(&#39;&#39;).reverse().join(&#39;&#39;));<br>    // If reversed number exceeds the 32-bit max value, return 0<br>    if (reversed &gt; 0x7FFFFFFF) return 0;<br>    // Return negative reversed number if input was negative<br>    return isNegative ? -reversed : reversed;<br>};</pre><h3>✅ Explanation</h3><ul><li>Convert to string, reverse with split().reverse().join().</li><li>Use parseInt to convert back.</li><li>Check against max 32-bit integer (0x7FFFFFFF).</li></ul><h3>🧠 Key Learnings</h3><ul><li>Understand 32-bit integer overflow boundaries.</li><li>Always check for overflow <strong>after</strong> operations.</li><li>Use built-in methods (like strrev, slicing, or string reversal) smartly.</li><li>Optimize for <strong>time (O(log N))</strong> and <strong>space (O(1) if done numerically)</strong>.</li></ul><h3>🏁 Final Thoughts</h3><p>The Reverse Integer problem may seem simple at first, but it teaches you <strong>defensive programming</strong>, <strong>bit manipulation awareness</strong>, and <strong>working with edge cases</strong>.</p><p>This question is a great warm-up for more advanced number manipulation problems like <strong>Palindrome Numbers</strong>, <strong>Integer to Roman</strong>, or <strong>String to Integer</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8aa2aba35d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Solve the Two Sum Challenge on LeetCode]]></title>
            <link>https://medium.com/@studylearnandfun/how-to-solve-the-two-sum-challenge-on-leetcode-d1769de305ef?source=rss-070deb50d45d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1769de305ef</guid>
            <category><![CDATA[two-sum-problem]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-question]]></category>
            <category><![CDATA[leetcode-answer]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <dc:creator><![CDATA[Studylearnandfun]]></dc:creator>
            <pubDate>Mon, 26 May 2025 19:30:36 GMT</pubDate>
            <atom:updated>2025-05-26T19:30:36.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfAbDA5LK47DfOE8Fd9ruQ.png" /></figure><h3>🧩 Two Sum — Explained simply</h3><h3>🚀 Difficulty: Easy | 💼 Asked in Many Interviews</h3><h3>📘 The Problem (from LeetCode)</h3><blockquote><strong><em>Given</em></strong><em> an array of integers </em><em>nums and an integer </em><em>target, return the </em><strong><em>indices of the two numbers</em></strong><em> such that they add up to </em><em>target.</em></blockquote><p>You <strong>must</strong>:</p><ul><li>Return <strong>exactly one solution</strong> (you can assume there is always one)</li><li>Not use the same element <strong>twice</strong></li><li>Return the <strong>indexes</strong> (positions) of the numbers, not the numbers themselves</li><li>The order of the result doesn’t matter</li></ul><h3>💡 Let’s Understand With an Example:</h3><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>We need to find two numbers from the array whose sum is 9.</p><p>Let’s try:</p><ul><li>2 + 7 = ✅ 9 → Found at index <strong>0 and 1</strong></li></ul><p>Answer: [0, 1]</p><h3>🎓 Real-Life Analogy:</h3><p>Imagine you’re shopping. Your friend gives you ₹9 and a list of item prices. You need to pick <strong>2 items</strong> that <strong>exactly total ₹9</strong>.</p><p>Item prices = [2, 7, 11, 15]<br>You pick ₹2 (item at index 0) and ₹7 (index 1). That’s the answer → [0, 1].</p><h3>❗ Common Misunderstanding</h3><p>Some people only check each element and the <strong>next</strong> one (i and i+1). But what if the answer is in some other pair (like index 1 and 3)? That logic will <strong>miss</strong> some valid answers.</p><p>We need to try <strong>every pair</strong>, not just adjacent ones.</p><h3>🧐 Solution 1: Brute Force (Beginner Friendly)</h3><p>Try every possible pair of numbers. If their sum is the target, return their indexes.</p><h3>🧮 Logic:</h3><ul><li>Loop over each number with index i</li><li>Inside that loop, loop over every number after i (index j)</li><li>Check if nums[i] + nums[j] == target</li><li>If yes, return [i, j]</li></ul><h3>🕐 Time Complexity:</h3><ul><li>O(n^2) (nested loops)</li></ul><h3>🧠 Pseudocode:</h3><pre>Loop i from 0 to length-1<br>    Loop j from i+1 to length<br>        if nums[i] + nums[j] == target<br>            return [i, j]</pre><h3>💻 PHP Code (With Comments)</h3><pre>class Solution {<br>    function twoSum($nums, $target) {<br>        $n = count($nums); // Get the size of the array<br>        for ($i = 0; $i &lt; $n; $i++) {<br>            for ($j = $i + 1; $j &lt; $n; $j++) {<br>                // Check if this pair sums up to the target<br>                if ($nums[$i] + $nums[$j] == $target) {<br>                    return [$i, $j]; // Return their positions<br>                }<br>            }<br>        }<br>        return []; // Return empty if no pair found<br>    }<br>}</pre><h3>☕ Java Code</h3><pre>class Solution {<br>    public int[] twoSum(int[] nums, int target) {<br>        int n = nums.length;<br>        for (int i = 0; i &lt; n; i++) {<br>            for (int j = i + 1; j &lt; n; j++) {<br>                if (nums[i] + nums[j] == target) {<br>                    return new int[] { i, j };<br>                }<br>            }<br>        }<br>        return new int[] {};<br>    }<br>}</pre><h3>🐍 Python Code</h3><pre>class Solution:<br>    def twoSum(self, nums, target):<br>        n = len(nums)<br>        for i in range(n):<br>            for j in range(i + 1, n):<br>                if nums[i] + nums[j] == target:<br>                    return [i, j]<br>        return []</pre><h3>🌐 JavaScript Code</h3><pre>function twoSum(nums, target) {<br>    for (let i = 0; i &lt; nums.length; i++) {<br>        for (let j = i + 1; j &lt; nums.length; j++) {<br>            if (nums[i] + nums[j] === target) {<br>                return [i, j];<br>            }<br>        }<br>    }<br>    return [];<br>}</pre><h3>💡 Solution 2: Optimized Using Hash Map (For Faster Performance)</h3><p>Instead of checking every pair, we can:</p><ul><li>Use a hash map to remember numbers we’ve already seen</li><li>For each number, check if target - current number already exists in the map</li></ul><h3>✅ Time: O(n), Space: O(n)</h3><h3>Python (Optimized):</h3><pre>class Solution:<br>    def twoSum(self, nums, target):<br>        seen = {}<br>        for i, num in enumerate(nums):<br>            complement = target - num<br>            if complement in seen:<br>                return [seen[complement], i]<br>            seen[num] = i</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVlb_UI0I1IM1b5m7ekoSw.png" /></figure><h3>📒 Final Tips</h3><ul><li>Master brute force first → it’s simple and helps understand the problem.</li><li>Later, try to learn the <strong>hash map method</strong> — it’s fast and often asked in interviews.</li><li>Practice writing in <strong>multiple languages</strong> (like we just did!) — great for polyglot devs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1769de305ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>