Posted on

Parenthesis Checker

Given a string s, composed of different combinations of ‘(‘ , ‘)’, ‘{‘, ‘}’, ‘[‘, ‘]’, verify the validity of the arrangement.
An input string is valid if:

         1. Open brackets must be closed by the same type of brackets.
         2. Open brackets must be closed in the correct order.

Examples :

Input: s = "[{()}]"
Output: true
Explanation: All the brackets are well-formed.
Input: s = "[()()]{}"
Output: true
Explanation: All the brackets are well-formed.
Input: s = "([]"
Output: False
Explanation: The expression is not balanced as there is a missing ')' at the end.
Input: s = "([{]})"
Output: False
Explanation: The expression is not balanced as there is a closing ']' before the closing '}'.

Constraints:
1 ≤ s.size() ≤ 106
s[i] ∈ {‘{‘, ‘}’, ‘(‘, ‘)’, ‘[‘, ‘]’}


class Solution {
  public:
    bool isBalanced(string& s) {

        stack<char> st;
        unordered_map<char,char> mp = {
            {'{','}'},
            {'(',')'},
            {'[',']'}
        };
        
        
        
        for( char c:s ) {
            
            if( mp.count(c) )
                st.push(c);
                
            else {
                
                if( st.empty() || mp[st.top()] != c ) 
                    return false;
                    
                st.pop();
            }
            
            
        }
        
        return st.empty();
        
    }
};
Posted on

Stock Span

The stock span problem is a financial problem where we have a series of daily price quotes for a stock and we need to calculate the span of stock price for all days. The span arr[i] of the stocks price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the given day is less than or equal to its price on the current day.

Examples:

Input: arr[] = [100, 80, 60, 70, 60, 75, 85]
Output: [1, 1, 1, 2, 1, 4, 6]
Explanation: Traversing the given input span 100 is greater than equal to 100 and there are no more elements behind it so the span is 1, 80 is greater than equal to 80 and smaller than 100 so the span is 1, 60 is greater than equal to 60 and smaller than 80 so the span is 1, 70 is greater than equal to 60,70 and smaller than 80 so the span is 2 and so on.  Hence the output will be 1 1 1 2 1 4 6.
Input: arr[] = [10, 4, 5, 90, 120, 80]
Output: [1, 1, 2, 4, 5, 1]
Explanation: Traversing the given input span 10 is greater than equal to 10 and there are no more elements behind it so the span is 1, 4 is greater than equal to 4 and smaller than 10 so the span is 1, 5 is greater than equal to 4,5 and smaller than 10 so the span is 2,  and so on. Hence the output will be 1 1 2 4 5 1.
Input: arr[] = [11, 4, 5, 90, 120, 80]
Output: [1, 1, 2, 4, 5, 1]
Explanation: Traversing the given input span 11 is greater than equal to 11 and there are no more elements behind it so the span is 1, 4 is greater than equal to 4 and smaller than 10 so the span is 1, 5 is greater than equal to 4,5 and smaller than 10 so the span is 2, and so on. Hence the output will be 1 1 2 4 5 1.

Constraints:
1 ≤ arr.size()≤ 105
1 ≤ arr[i] ≤ 105


//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
  public:
    bool isBalanced(string& s) {
        // code here
        stack<char> st;
        unordered_map<char,char> mp;
        mp.set('{','}');
        mp.set('(',')');
        mp.set('[',']');
        
        
        for( char c:s ){
            
            if( mp[st.top()] == c )
                    st.pop();
            } else
                st.push(c);
                
        }
        
        return st.size() == 0;
        
    }
};
//{ Driver Code Starts.
int main() {
    int t;
    string a;
    cin >> t;
    while (t--) {
        cin >> a;
        Solution obj;
        if (obj.isBalanced(a))
            cout << "true" << endl;
        else
            cout << "false" << endl;
        cout << "~"
             << "\n";
    }
}
// } Driver Code Ends
Posted on

Construct the Smallest Number

Developers flex on each with the strangest of ways. How green is your github commit history. Have you submitted a PR to a open source project. How well can you solve the silliest questions on leetcode / geeksforgeeks / hackerrank?
While normies use money and status as a measure of success. Coders have incelled their way into a paradise where the glow of the monitor is all you need.
Pray for death all you want, it’s not coming. Man up and start grinding.

You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.

0-indexed string num of length n + 1 is created using the following conditions:

  • num consists of the digits '1' to '9', where each digit is used at most once.
  • If pattern[i] == 'I', then num[i] < num[i + 1].
  • If pattern[i] == 'D', then num[i] > num[i + 1].

Return the lexicographically smallest possible string num that meets the conditions.

Example 1:

Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.

Example 2:

Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.

Constraints:

  • 1 <= pattern.length <= 8
  • pattern consists of only the letters 'I' and 'D'.

class Solution {
public:
    string smallestNumber(string pattern) {
        string result;
        stack<int> st;
        for( int i = 0; i<= pattern.size(); i++ ){
            st.push(i+1);
             if ( i == pattern.length() || pattern[i] == 'I' )
                while(!st.empty()){
                    result+=to_string( st.top() );
                    st.pop();        
                }
                
        }
        return result;
    }
};
Posted on

Generating Subsets using Backtracking

1863. Sum of All Subset XOR Totals
This is a good problem to grasp basics of backtracking

The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.

  • For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.

Given an array nums, return the sum of all XOR totals for every subset of nums

Note: Subsets with the same elements should be counted multiple times.

An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.

Example 1:

Input: nums = [1,3]
Output: 6
Explanation: The 4 subsets of [1,3] are:
- The empty subset has an XOR total of 0.
- [1] has an XOR total of 1.
- [3] has an XOR total of 3.
- [1,3] has an XOR total of 1 XOR 3 = 2.
0 + 1 + 3 + 2 = 6

Example 2:

Input: nums = [5,1,6]
Output: 28
Explanation: The 8 subsets of [5,1,6] are:
- The empty subset has an XOR total of 0.
- [5] has an XOR total of 5.
- [1] has an XOR total of 1.
- [6] has an XOR total of 6.
- [5,1] has an XOR total of 5 XOR 1 = 4.
- [5,6] has an XOR total of 5 XOR 6 = 3.
- [1,6] has an XOR total of 1 XOR 6 = 7.
- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28

Example 3:

Input: nums = [3,4,5,6,7,8]
Output: 480
Explanation: The sum of all XOR totals for every subset is 480.

class Solution {
    vector<vector<int>> subset;
    void backtrack(vector<int> &nums,vector<int> &current,int index){
        subset.push_back(current);
        for(int i = index; i < nums.size(); i++ ){
            current.push_back(nums[i]);
            backtrack( nums,  current, i+1);
            current.pop_back();
        }
    }
public:
    
    int subsetXORSum(vector<int>& nums) {
        vector<int> current;
        backtrack(nums,current,0);
        
        int total_sum = 0;
        for (const auto& sub : subset) {
            int xor_sum = 0;
            for (int num : sub) {
                //std::cout<<num<<" ";
                xor_sum ^= num;
            }
            //std::cout<<std::endl;
            total_sum += xor_sum;
        }
        
        return total_sum;
    }
};
Posted on

k largest elements

Given an array arr[] of positive integers and an integer k, Your task is to return k largest elements in decreasing order. 

Examples:

Input: arr[] = [12, 5, 787, 1, 23], k = 2
Output: [787, 23]
Explanation: 1st largest element in the array is 787 and second largest is 23.
Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3 
Output: [50, 30, 23]
Explanation: Three Largest elements in the array are 50, 30 and 23.
Input: arr[] = [12, 23], k = 1
Output: [23]
Explanation: 1st Largest element in the array is 23.

Constraints:
1 ≤ k ≤ arr.size() ≤ 106
1 ≤ arr[i] ≤ 106


class Solution {
    
    std::vector<int> minHeapToVector(std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap) {
        std::vector<int> result;
        while (!minHeap.empty()) {
            result.push_back(minHeap.top());
            minHeap.pop();
        }
        std::reverse(result.begin(), result.end());
        return result;
    }
    
  public:
    vector<int> kLargest(vector<int>& arr, int k) {
        
        std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
        
        for( int i : arr ){
            if( minHeap.size() < k )
                minHeap.push(i);
            else if( minHeap.top()<=i ){
                minHeap.pop();
                minHeap.push(i);
            }
        }
        
        return  minHeapToVector(minHeap);
        
    }
    
};
Posted on

1079. Letter Tile Possibilities

You have n  tiles, where each tile has one letter tiles[i] printed on it.

Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.

Example 1:

Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Example 2:

Input: tiles = "AAABBC"
Output: 188

Example 3:

Input: tiles = "V"
Output: 1

Depth First Search Solution, which is more performant with time complexity of O(N!) and space complexity of O(N).

class Solution {
public:
    int numTilePossibilities(string tiles) {
        unordered_map<char, int> count;
        for (char c : tiles) {
            count[c]++;
        }
        return dfs(count);
    }
    
private:
    int dfs(unordered_map<char, int>& count) {
        int sum = 0;
        for (auto& [tile, cnt] : count) {
            if (cnt == 0) continue;
            sum++;
            count[tile]--;
            sum += dfs(count);
            count[tile]++;
        }
        return sum;
    }
};

Backtracking Solution:

class Solution {
private: 
    set<string> seq;
    void backtrack(const string& tiles, string& current, vector<bool>& used){
        if( !current.empty() )
            seq.insert( current );
        for( int i =0; i<tiles.length();i++){
            if(used[i]) continue;
            used[i]=true;
            current.push_back(tiles[i]);
            backtrack(tiles, current, used);
            current.pop_back();
            used[i]=false;
        }
    }
public:
    
    int numTilePossibilities(string tiles) {
        vector<bool> used(tiles.length(), false);
        string current = "";        
        backtrack(tiles, current, used);
        return seq.size();
    }
};

Optimized Backtracking solution:


class Solution {
public:
void backtrack(unordered_map<char,int>&mapi,int &count){
    for(auto&entry:mapi){
    if(entry.second>0){
        entry.second--;
        count++;
        backtrack(mapi,count);
        entry.second++;
    }
    }
}
    int numTilePossibilities(string tiles) {
        unordered_map<char,int>mapi;
        for(int i=0;i<tiles.size();i++){
            mapi[tiles[i]]++;
        }
        int count=0;
         backtrack(mapi,count);
         return count;
    }
};

Posted on

LeetCode 1718. Construct the Lexicographically Largest Valid Sequence

Solution is a greedy recursion. Iterate in reverse order to make sure to get the largest solution first.


function constructDistancedSequence(n: number): number[] {
    const size = 2 * n - 1;
    const result: number[] = new Array(size).fill(0);
    const used: boolean[] = new Array(n + 1).fill(false);
    function backtrack(index: number): boolean {
        if (index === size) return true; // If we filled the array, return success
        if (result[index] !== 0) return backtrack(index + 1); // Skip filled positions
        for (let num = n; num >= 1; num--) { // Try from largest to smallest
            if (used[num]) continue;
            if (num === 1) {
                // Place 1 (only once)
                result[index] = 1;
                used[1] = true;
                if (backtrack(index + 1)) return true;
                used[1] = false;
                result[index] = 0;
            } else {
                // Place num at index and index + num (if valid)
                if (index + num < size && result[index + num] === 0) {
                    result[index] = result[index + num] = num;
                    used[num] = true;
                    if (backtrack(index + 1)) return true;
                    used[num] = false;
                    result[index] = result[index + num] = 0;
                }
            }
        }
        return false;
    }
    backtrack(0);
    return result;
}
Posted on

List of Open Source C++ Games

Yeah, there are plenty of open-source C++ games that run on Linux and can help you learn game development. Here are a few solid ones:

  1. Godot Engine (with C++ modules) – While Godot mainly uses GDScript, you can extend it with C++ for performance-critical parts. Check out its source code here.
  2. SuperTux – A classic side-scrolling platformer similar to Super Mario. Its codebase is relatively easy to understand for beginners. Repo: https://github.com/SuperTux/supertux.
  3. Battle for Wesnoth – A turn-based strategy game with a well-structured C++ codebasFor physics engines and networking in C++, these open-source games and engines will be really useful:
  4. Box2D – Not a game, but a powerful 2D physics engine used in many games. Studying its code will teach you how physics simulations work. Repo: https://github.com/erincatto/box2d.
  5. Bullet Physics – A widely used physics engine for 3D games, including real-time simulations. Repo: https://github.com/bulletphysics/bullet3.
  6. Godot Engine (C++ modules) – While primarily using GDScript, Godot allows custom physics and networking via C++. Repo: https://github.com/godotengine/godot.
  7. Torque 3D – A full-featured game engine with built-in physics (Bullet) and networking. Repo: https://github.com/TorqueGameEngines/Torque3D.
  8. OpenTTD – A transport simulation game with multiplayer networking. The networking code is well-structured and useful for learning. Repo: https://github.com/OpenTTD/OpenTTD.
  9. Teeworlds – A 2D multiplayer shooter with networking and physics interactions. It has a clean and efficient network implementation. Repo: https://github.com/teeworlds/teeworlds.
  10. For pure networking, you might also want to look into ENet (https://github.com/lsalzman/enet), which is a simple and lightweight networking library used in many multiplayer games.e, useful for learning AI, networking, and game mechanics. Repo: https://github.com/wesnoth/wesnoth.
  11. 0 A.D. – A real-time strategy game with a highly professional C++ codebase. If you’re interested in complex game development, this is a great resource. Repo: https://github.com/0ad/0ad.
  12. OpenRA – A modernized engine for old Command & Conquer games. It’s great for learning about game engines and networking. Repo: https://github.com/OpenRA/OpenRA.

Posted on

3174. Clear Digits

You are given a string s. Your task is to remove all digits by doing this operation repeatedly: Delete the first digit and the closest non-digit character to its left. Return the resulting string after removing all digits.

Example 1:

Input: s = “abc”
Output: “abc”

Explanation:

There is no digit in the string.

Example 2:

Input: s = “cb34”
Output: “”

Explanation:

First, we apply the operation on s[2], and s becomes "c4".
Then we apply the operation on s[1], and s becomes "".

Constraints:

  • 1 <= s.length <= 100
  • s consists only of lowercase English letters and digits.
  • The input is generated such that it is possible to delete all digits.

    string clearDigits(string s) {
        stack<char> sc;
        string result = "";
        for( char c : s ){
            if( c >= 48 && c <=57 ){
                sc.pop();
            } else
                sc.push(c);
        }
        while( !sc.empty() ){
            result+= sc.top();
            sc.pop();
        }
        reverse( result.begin(), result.end());
        return result;
    }