Skip to main content

Command Palette

Search for a command to run...

Easy LeetCode Problems: A Friendly Guide

Published
6 min readView as Markdown
A

I am a passionate web developer and open-source enthusiast on a captivating journey of coding wonders. With a year of experience in web development, my curiosity led me to the enchanting world of React, where I found a true calling. Embracing the magic of collaboration and knowledge-sharing, I ventured into the realm of open source, contributing to Digital Public Goods (DPGs) for the betterment of the digital universe. A firm believer in learning in public, I share my insights and discoveries through blogging, inspiring fellow coders to embark on their own magical coding odysseys. Join me on this thrilling adventure, where imagination and technology converge, and together, let's shape the future of the digital landscape! 🎩✨

Screenshot:-

LeetCode is a fantastic platform to practice coding problems and improve your problem-solving skills. Today, we'll go through five easy-level LeetCode problems: Two Sum, Reverse Integer, Palindrome Number, Merge Two Sorted Lists, and Valid Parentheses. We'll explain the approach for each problem and provide the solution in a friendly and understandable way. Let's dive in!

Activity 1: Two Sum

Problem: Given an array of numbers and a target number, return the indices of the two numbers that add up to the target.

Approach:

  1. Understanding the problem: We need to find two numbers in the array that sum up to the target number and return their indices.

  2. Plan: Use a hash map to store the difference between the target and each number as we iterate through the array. This allows us to check if the required number to reach the target is already in the map.

Code:

#include <vector>
#include <unordered_map>
#include <iostream>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> numMap;
        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];
            if (numMap.find(complement) != numMap.end()) {
                return {numMap[complement], i};
            }
            numMap[nums[i]] = i;
        }
        return {};
    }
};

// Test cases
int main() {
    Solution sol;
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;
    vector<int> result = sol.twoSum(nums, target);
    cout << "Indices: " << result[0] << ", " << result[1] << endl;  // Output: 0, 1
    return 0;
}

Important Points:

  • We use a hash map for efficient lookup.

  • We check if the complement (target - current number) is already in the hash map.

  • This approach has a time complexity of O(n).

Activity 2: Reverse Integer

Problem: Given an integer, return it with its digits reversed. Handle edge cases like negative numbers and numbers ending in zero.

Approach:

  1. Understanding the problem: We need to reverse the digits of the integer.

  2. Plan: Use mathematical operations to extract and reverse the digits. Handle edge cases where the reversed integer might overflow.

Code:

#include <iostream>
#include <limits.h>

using namespace std;

class Solution {
public:
    int reverse(int x) {
        long reversed = 0;
        while (x != 0) {
            int digit = x % 10;
            reversed = reversed * 10 + digit;
            x /= 10;
            if (reversed > INT_MAX || reversed < INT_MIN) return 0;
        }
        return static_cast<int>(reversed);
    }
};

// Test cases
int main() {
    Solution sol;
    int number = 123;
    cout << "Reversed: " << sol.reverse(number) << endl;  // Output: 321
    return 0;
}

Important Points:

  • Use long to handle potential overflow before casting back to int.

  • Check for overflow conditions and return 0 if overflow occurs.

Activity 3: Palindrome Number

Problem: Given an integer, return true if it is a palindrome, and false otherwise.

Approach:

  1. Understanding the problem: A palindrome reads the same backward as forward.

  2. Plan: Convert the integer to a string and check if it reads the same backward.

Code:

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        string str = to_string(x);
        int left = 0, right = str.size() - 1;
        while (left < right) {
            if (str[left] != str[right]) return false;
            left++;
            right--;
        }
        return true;
    }
};

// Test cases
int main() {
    Solution sol;
    int number = 121;
    cout << "Is Palindrome: " << (sol.isPalindrome(number) ? "true" : "false") << endl;  // Output: true
    return 0;
}

Important Points:

  • Convert the integer to a string to easily check palindrome properties.

  • Handle negative numbers by returning false immediately.

Activity 4: Merge Two Sorted Lists

Problem: Given two sorted linked lists, return a new sorted list by merging them.

Approach:

  1. Understanding the problem: We need to merge two sorted linked lists into one sorted linked list.

  2. Plan: Use a dummy node to simplify the merging process and compare nodes from both lists one by one.

Code:

#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode* current = &dummy;

        while (l1 != NULL && l2 != NULL) {
            if (l1->val <= l2->val) {
                current->next = l1;
                l1 = l1->next;
            } else {
                current->next = l2;
                l2 = l2->next;
            }
            current = current->next;
        }
        current->next = (l1 != NULL) ? l1 : l2;
        return dummy.next;
    }
};

// Test cases
void printList(ListNode* node) {
    while (node != NULL) {
        cout << node->val << " ";
        node = node->next;
    }
    cout << endl;
}

int main() {
    Solution sol;
    ListNode* l1 = new ListNode(1);
    l1->next = new ListNode(2);
    l1->next->next = new ListNode(4);

    ListNode* l2 = new ListNode(1);
    l2->next = new ListNode(3);
    l2->next->next = new ListNode(4);

    ListNode* mergedList = sol.mergeTwoLists(l1, l2);
    printList(mergedList);  // Output: 1 1 2 3 4 4
    return 0;
}

Important Points:

  • Use a dummy node to simplify the merging process.

  • Compare nodes from both lists and attach the smaller node to the current node.

Activity 5: Valid Parentheses

Problem: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Approach:

  1. Understanding the problem: A string is valid if open brackets are closed in the correct order.

  2. Plan: Use a stack to keep track of opening brackets and ensure they are closed correctly.

Code:

#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;

class Solution {
public:
    bool isValid(string s) {
        stack<char> stack;
        unordered_map<char, char> brackets = {{')', '('}, {'}', '{'}, {']', '['}};

        for (char c : s) {
            if (brackets.find(c) != brackets.end()) {
                if (stack.empty() || stack.top() != brackets[c]) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        return stack.empty();
    }
};

// Test cases
int main() {
    Solution sol;
    string str = "()[]{}";
    cout << "Is Valid: " << (sol.isValid(str) ? "true" : "false") << endl;  // Output: true
    return 0;
}

Important Points:

  • Use a stack to keep track of opening brackets.

  • Ensure that each closing bracket matches the top of the stack.

Conclusion

By solving these five LeetCode problems, you've practiced important concepts like hash maps, stacks, and linked lists. These problems are great for building a strong foundation in algorithmic thinking and problem-solving. Keep practicing, and you'll gain confidence in tackling even more challenging coding problems!


Feel free to use this article format for your blog or to share it with others who are learning to solve coding problems on LeetCode. Happy coding!

More from this blog

Untitled Publication

33 posts