Skip to content

Commit 34ae936

Browse files
author
dushimsam
committed
challenge(DP): get min spaces in Pi
1 parent f75a09b commit 34ae936

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
typedef unordered_map<int, int> mp;
4+
5+
int getMinSpaces(string pi, set<string> numbersTable, mp &cache, int idx)
6+
{
7+
// return -1 if the number on which we called this fn was the last one
8+
if (idx == pi.length())
9+
return -1;
10+
// check if the value for this particular idx already exists in the cache, so that we don't make unnecessary repetition
11+
if (cache.find(idx) != cache.end())
12+
return cache.at(idx);
13+
// declare the minSpaces variable for this particular idx
14+
int minSpaces = INT_MAX;
15+
// iterate from this current idx to the end, trying to minimize the space
16+
for (int i = idx; i < pi.length(); i++)
17+
{
18+
// create a prefix - from this idx back to the end
19+
string prefix = pi.substr(idx, i + 1 - idx);
20+
// check if the prefix exists in the set 'numbersTable'
21+
if (numbersTable.find(prefix) != numbersTable.end())
22+
{
23+
// reduce the existing spaces
24+
int minSpacesInSuffix = getMinSpaces(pi, numbersTable, cache, i + 1);
25+
26+
// Handle int overflow
27+
if (minSpacesInSuffix == INT_MAX)
28+
{
29+
minSpaces = min(minSpacesInSuffix, minSpaces);
30+
}
31+
else
32+
{
33+
minSpaces = min(minSpaces, minSpacesInSuffix + 1);
34+
}
35+
}
36+
}
37+
// insert the min spaces for this idx
38+
cache.insert({idx, minSpaces});
39+
// return the min spaces for the idx
40+
return cache.at(idx);
41+
}
42+
43+
int numbersInPi(string pi, vector<string> numbers)
44+
{
45+
// create the set to store the numberse
46+
set<string> numbersTable;
47+
// insert numbers in the set
48+
for (string num : numbers)
49+
{
50+
numbersTable.insert(num);
51+
}
52+
mp cache;
53+
// lead numbers from the back to the front
54+
for (int i = pi.length() - 1; i >= 0; i--)
55+
{
56+
// for each number fill up the minSpaces for it. by Calling getMinSpaces function
57+
getMinSpaces(pi, numbersTable, cache, i);
58+
}
59+
// return the minSpaces from the cache located at 0' index
60+
return cache.at(0) == INT_MAX ? -1 : cache.at(0);
61+
}
62+
63+
int main()
64+
{
65+
66+
string pi = "3141592653589793238462643383279";
67+
vector<string> nums = {"314159265358979323846", "26433", "8", "3279", "314159265", "35897932384626433832", "79"};
68+
// Expected result - 2
69+
cout << numbersInPi(pi, nums) << endl;
70+
return 0;
71+
}

0 commit comments

Comments
 (0)