Skip to content

Commit

Permalink
uses Memoization and reduces space (#344)
Browse files Browse the repository at this point in the history
* uses Memoization and reduces space

* Avoids recursion stack overhead by using an iterative approach

* Replaces multiple if statements with a switch statement for better readability and efficiency.
  • Loading branch information
Anshuman7080 authored Oct 12, 2024
1 parent a7c137f commit a3d8734
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 93 deletions.
63 changes: 11 additions & 52 deletions C++/AdjacentBitCounts.cpp
Original file line number Diff line number Diff line change
@@ -1,74 +1,35 @@
/**
* Problem:- Adjacent Bit Counts
* Link: https://www.spoj.com/problems/GNYR09F/
*/

/**
* Explaination:-
*
* State Representation: We will define a dynamic programming (DP) state dp[n][k][last]:
* n: The current length of the bit string.
* k: The remaining adjacent bit count to satisfy.
* last: The last bit of the string (either 0 or 1)
*
* Base Cases:
* If n == 1 and k == 0, there is only one valid bit string (either "0" or "1"), but no adjacent pairs can exist for n == 1.
* If k > 0 when n == 1, it's impossible to satisfy, so return 0 in that case.
*
* Recursive-Calls:
* If the current bit is 1, the previous bit could either be 1 (which would contribute to the adjacent bit count) or 0.
* If the current bit is 0, the previous bit could either be 0 or 1 (but no adjacent bit count is added).
*/

#include <iostream>
#include <cstring> // For memset
#include <cstring>
using namespace std;
#define ll long long int

// DP table where dp[n][k][last] represents the number of ways to get a bit string of length n with exactly k adjacent '1's ending in 'last' (0 or 1)
ll dp[1001][101][2];

/**
* Time complexity: (N*K*2) => (N*K)
* Space complexity: (N*K*2) => (N*K)
*/
ll dp[101][101][2];

// Function to calculate the number of valid bit strings
ll ftd(int n, int k, int last){ // function-of-top-down
ll ftd(int n, int k, int last) {
// Base case: If n is 1, we can only have a single bit string
if (n == 1)
{
// If we want 0 adjacent pairs, it's valid if k == 0
if (k == 0){
return 1;
}
return 0;
if (n == 1) {
return k == 0 ? 1 : 0;
}

// If we have already solved this subproblem, return the result
if (dp[n][k][last] != -1){
if (dp[n][k][last] != -1) {
return dp[n][k][last];
}


// Initialize the result for the current state
ll ans = 0;

// If the current bit is 1, we consider two possibilities:
// 1. The previous bit was also 1 (adds to adjacent count).
// 2. The previous bit was 0 (no adjacent 1s added).
if (last == 1)
{
// We can only decrement k if we place a '1' next to another '1'.
if (k > 0)
{
if (last == 1) {
if (k > 0) {
ans += ftd(n - 1, k - 1, 1); // Case when previous bit was 1 (k-1)
}
ans += ftd(n - 1, k, 0); // Case when current bit was 0 (k remains the same)
}
// If the last bit is 0, we can append a '0' or '1' to the previous part of the string.
else
{
} else {
ans += ftd(n - 1, k, 0); // Current bit was also 0 (k stays the same)
ans += ftd(n - 1, k, 1); // Current bit was 1 (k stays the same)
}
Expand All @@ -77,13 +38,11 @@ ll ftd(int n, int k, int last){ // function-of-top-down
return dp[n][k][last] = ans;
}

int main()
{
int main() {
int t;
cin >> t; // Number of test cases

while (t--)
{
while (t--) {
int number_of_test_case, n, k;
cin >> number_of_test_case >> n >> k;

Expand Down
48 changes: 23 additions & 25 deletions C++/LCAinBinaryTree.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// C++ program to print right view of Binary Tree
// using recursion
#include <bits/stdc++.h>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

class Node {
Expand All @@ -14,30 +14,29 @@ class Node {
}
};

void RecursiveRightView(Node* root, int level,
int& maxLevel, vector<int>& result) {
if (!root) return;

if (level > maxLevel) {
result.push_back(root->data);
maxLevel = level;
}

RecursiveRightView(root->right, level + 1,
maxLevel, result);
RecursiveRightView(root->left, level + 1,
maxLevel, result);
}

vector<int> rightView(Node *root) {
vector<int> rightView(Node* root) {
vector<int> result;
int maxLevel = -1;
RecursiveRightView(root, 0, maxLevel, result);

if (!root) return result;

queue<Node*> q;
q.push(root);

while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; ++i) {
Node* node = q.front();
q.pop();
if (i == n - 1) {
result.push_back(node->data);
}
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return result;
}

void printArray(vector<int>& arr) {
void printArray(const vector<int>& arr) {
for (int val : arr) {
cout << val << " ";
}
Expand All @@ -52,8 +51,7 @@ int main() {
root->right->right = new Node(5);

vector<int> result = rightView(root);

printArray(result);

return 0;
}
37 changes: 21 additions & 16 deletions C++/ValidParentheses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,32 @@

class Solution {
public:
bool isValid(std::string s) {
std::stack<char> mp;
bool isValid(const std::string& s) {
std::stack<char> stack;

for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
mp.push(c);
} else {
if (mp.empty()) {
return false;
}
if ((c == ')' && mp.top() == '(') ||
(c == ']' && mp.top() == '[') ||
(c == '}' && mp.top() == '{')) {
mp.pop();
} else {
return false;
}
switch (c) {
case '(': case '[': case '{':
stack.push(c);
break;
case ')':
if (stack.empty() || stack.top() != '(') return false;
stack.pop();
break;
case ']':
if (stack.empty() || stack.top() != '[') return false;
stack.pop();
break;
case '}':
if (stack.empty() || stack.top() != '{') return false;
stack.pop();
break;
default:
return false; // Invalid character
}
}

return mp.empty();
return stack.empty();
}
};

Expand Down

0 comments on commit a3d8734

Please sign in to comment.