Skip to content

Commit 5d6c3a1

Browse files
committed
Merge branch 'master' of https://github.com/smv1999/CompetitiveProgrammingQuestionBank into Devincept13
2 parents 9b6d82a + 328809f commit 5d6c3a1

File tree

4 files changed

+348
-0
lines changed

4 files changed

+348
-0
lines changed

Codechef Problems/Red_alert.c

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/* PROBLEM STATEMENT
2+
3+
4+
Finally a monsoon has come. According to the Meteorological Department, there will be rain in the upcoming N days in the city. Initially, the water level of the city is zero millimetres. The amount of rain on the i-th day can be described by an integer Ai as follows:
5+
6+
If Ai>0, the water level of the city increases by Ai millimetres on the i-th day.
7+
If Ai=0, there is no rain on the i-th day. The water level of the city decreases by D millimetres on such a day. However, if the water level is less than D millimetres before the i-th day, then it becomes zero instead.
8+
There will be a red alert in the city if the water level becomes strictly greater than H millimetres on at least one of the N days. Determine if there will be a red alert.
9+
10+
Input Format
11+
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
12+
The first line of each test case contains three space-separated integers N, D and H.
13+
The second line contains N space-separated integers A1,A2,…,AN.
14+
Output Format
15+
For each test case, print a single line containing the string "YES" if there will be a red alert or "NO" otherwise.
16+
17+
Constraints
18+
1≤T≤103
19+
1≤N,D≤102
20+
0≤Ai≤102 for each valid i
21+
1≤H≤104
22+
Subtasks
23+
Subtask #1 (100 points): original constraints
24+
25+
Sample Input 1
26+
4
27+
4 2 6
28+
1 3 0 2
29+
2 1 100
30+
1 100
31+
4 2 3
32+
1 2 0 2
33+
3 7 10
34+
5 3 9
35+
Sample Output 1
36+
NO
37+
YES
38+
NO
39+
YES
40+
Explanation
41+
Example case 1:
42+
43+
On the first day, the water level of the city increases to 1 millimtre.
44+
On the second day, the water level increases by 3 millimeters and becomes 1+3=4 millimtres.
45+
On the third day, there is no rain in the city, so the water level decreases by D=2 millimtres and becomes 4−2=2 millimtres.
46+
On the fourth day, the water level increases by 2 millimtres and becomes 2+2=4 millimtres.
47+
There will be no red alert in the city because the water level does not exceed H=6 millimtres on any of the four days.
48+
49+
Example case 2: The water level of the city on the 2-nd day is equal to 101 millimtres, which is greater than H=100 millimtres, so there will be a red alert in the city.
50+
51+
Example case 3: The water levels of the city on the four days are [1,3,1,3]. The water level is equal to H=3 millimtres on the second and fourth day, but it does not exceed the threshold.
52+
53+
Example case 4: There will be a red alert in the city on the 3-rd day. */
54+
55+
// SOLUTION
56+
57+
#include <stdio.h>
58+
59+
int main(void) {
60+
61+
int t,n,d,h;
62+
63+
scanf("%d",&t);
64+
// t represents the number of test cases
65+
66+
while(t--) //the loop runs for t times
67+
{
68+
scanf("%d %d %d",&n,&d,&h);
69+
// n, d and h respectively stores the input values
70+
int sum=0;int val; int ret=0;
71+
for(int i=0;i<n;i++) // this loop take n values as user input
72+
{
73+
74+
scanf("%d",&val); // the values inputted are stored each time in the variable val
75+
//note: here a single variable is used instead of an array beacuse the operations are done on the variable here itself i.e. within this loop.
76+
if(val>0)
77+
{
78+
//if val( the level of water on ith day > 0
79+
sum+=val; // total level = previous(stored in sum itsef) + val;
80+
81+
}
82+
if(val==0)
83+
{
84+
//if val( the level of water on ith day = 0
85+
sum=(sum<d)?0 : (sum-d);
86+
// the ternary operator above checks if sum<d for true: sum =0 for false: sum-d
87+
}
88+
89+
if(sum>h) //checks the level each day (level is calculated by carrying out arithmetic operations on variable val which is finally stored in variable sum
90+
{
91+
ret=1; //if red alert i.e. sum > h , the variable ret is initialised with value 1.
92+
break;
93+
}
94+
}
95+
if(ret==0)
96+
printf("NO\n");
97+
else
98+
printf("YES\n");
99+
// Time Complexity : O(N)
100+
// Space Complexity: 0(1)
101+
102+
}
103+
104+
105+
return 0;
106+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Given a string A of length n denoting an expression. It contains the following operators ’+’, ‘-‘, ‘*’, ‘/’.
2+
// Check whether A has redundant braces or not.
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
int redundantBraces(string A) {
8+
9+
int n= A.length();
10+
stack <char> s;
11+
12+
for(int i=0; i< n; i++)
13+
{
14+
//we'll push the operators and opening braces in the stack
15+
if(A[i]=='+' || A[i]=='-'|| A[i]=='/'|| A[i]=='*' || A[i]=='(' )
16+
s.push(A[i]);
17+
18+
//when we encounter closing braces, we need to start popping
19+
if(A[i]==')')
20+
{
21+
//if there are no operators, it means we have redundant braces for eg. ()
22+
if(s.top()=='(')
23+
return 1;
24+
25+
//else we start popping till we encounter opening braces
26+
//count variable will keep count of number of operators enclosed within the braces
27+
int count=0;
28+
while(!s.empty() && s.top()!='(')
29+
{
30+
s.pop();
31+
count++;
32+
}
33+
//count=0 means we have something like (a) which has redundant braces
34+
if(count==0)
35+
return 1;
36+
s.pop();
37+
}
38+
}
39+
40+
return 0;
41+
}
42+
43+
int main()
44+
{
45+
string str;
46+
cin>>str;
47+
if(redundantBraces(str))
48+
cout<<str+" has redundant braces";
49+
else
50+
cout<<str+" doesn't have any redundant braces";
51+
return 0;
52+
53+
}
54+
55+
// Test Cases
56+
// Input 1:
57+
// A = "((a + b))"
58+
// Output 1:
59+
// 1
60+
// Explanation 1:
61+
// ((a + b)) has redundant braces so answer will be 1.
62+
// Input 2:
63+
// A = "(a + (a + b))"
64+
// Output 2:
65+
// 0
66+
// Explanation 2:
67+
// (a + (a + b)) doesn't have have any redundant braces so answer will be 0.
68+
69+
// Time complexity: O(n)
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/* PROBLEM STATEMENT
2+
Given n names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers.
3+
You will then be given an unknown number of names to query your phone book for.
4+
For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber;
5+
if an entry for name is not found, print Not found instead.
6+
7+
Note: Your phone book should be a Dictionary/Map/HashMap data structure.
8+
9+
Input Format
10+
11+
The first line contains an integer,n , denoting the number of entries in the phone book.
12+
Each of the n subsequent lines describes an entry in the form of 2 space-separated values on a single line.
13+
The first value is a friend's name, and the second value is an 8-digit phone number.
14+
15+
After the n lines of phone book entries, there are an unknown number of lines of queries.
16+
Each line (query) contains a name to look up, and you must continue reading lines until there is no more input.
17+
18+
Note: Names consist of lowercase English alphabetic letters and are first names only.
19+
20+
Output Format
21+
22+
On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise,
23+
print the full name and phone number in the format name=phoneNumber.
24+
25+
Sample Input
26+
27+
3
28+
sam 99912222
29+
tom 11122222
30+
harry 12299933
31+
sam
32+
edward
33+
harry
34+
35+
Sample Output
36+
37+
sam=99912222
38+
Not found
39+
harry=12299933
40+
Explanation
41+
42+
We add the following n=3 (Key,Value) pairs to our map so it looks like this:
43+
phonebook={ (sam ,99912222),(tom, 11122222),(harry, 12299933)}
44+
45+
We then process each query and print key=value if the queried is found in the map; otherwise, we print Not found.
46+
47+
Query 0: sam
48+
Sam is one of the keys in our dictionary, so we print sam=99912222.
49+
50+
Query 1: edward
51+
Edward is not one of the keys in our dictionary, so we print Not found.
52+
53+
Query 2: harry
54+
Harry is one of the keys in our dictionary, so we print harry=12299933. */
55+
56+
57+
#include <cmath>
58+
#include <cstdio>
59+
#include <vector>
60+
#include <iostream>
61+
#include <algorithm>
62+
#include <map>
63+
using namespace std;
64+
65+
66+
int main() {
67+
68+
int n;
69+
string name;
70+
long num;
71+
cin >> n;
72+
cin.ignore();
73+
map <string, long> pBook;
74+
for (int i = 0; i < n; i++) {
75+
cin >> name;
76+
cin >> num;
77+
pBook[name] = num;
78+
}
79+
while(cin >> name) {
80+
if (pBook.find(name) != pBook.end())
81+
//pBook.end means that it has reached to the last element of pBook.
82+
//so if we use != , it means that it has not reached to the end. Thus it means that the name is found somewhere in the middle of pBook.
83+
{
84+
85+
cout << name << "=" << pBook.find(name)->second << endl;
86+
//map.find() iterates through your map structure. if it finds the element then it returns an iterator to that element else it returns end.
87+
//End being an element past the last element of that container, essentially telling you it wasn't found.
88+
//Remember containers in c++: arrays, vectors, maps, queues, stacks, etc. start at 0.
89+
//So if you have a map container with 10 elements and an index of 10 is returned this is outside the bounds of the container so in this function end is returned.
90+
91+
} else {
92+
cout << "Not found" << endl;
93+
}
94+
}
95+
return 0;
96+
}
97+
98+
// Time Comlexity: O(n)
99+
// Space Complexity: O(1)

Trie/Trie_add_Search_using_dict.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Purpose:
3+
4+
Implementation of Trie has been asked in my interviews like in Google
5+
Store word in Dictionary
6+
Search word in the dictionary returns True if exist
7+
Stores words in a compressed manner
8+
"""
9+
"""
10+
Inputs:
11+
1nd line no of word you want to store in Trie (int)
12+
2rd line to (2+1st line input)th line (string)
13+
Next line enter number of words want to search
14+
then enter strings in each line
15+
16+
"""
17+
class Trie:
18+
root = {} #main dictionary of Trie
19+
20+
def add(self, word): # This funtion adds new word to Trie
21+
cur = self.root # cur is iterator to check whether new key/paths are required to add new word and root is main dictionary
22+
23+
for ch in word: # ch is all the charactors in the word
24+
if ch not in cur: # if charactor is not present add new key/path initiate it empty
25+
cur[ch] = {}
26+
cur = cur[ch] # now go to the key that was created or was present
27+
cur['*'] = True # set * key to true at the end of each word
28+
#so larger the word the dictionary nesting will take place and * key represant the end state of the word
29+
30+
def search(self,word): # This function searches whether the word is presant or not presant
31+
cur = self.root #cur is iterator to check whether new key/paths are presant or not
32+
33+
for ch in word: # ch is all the charactors in the word
34+
if ch not in cur: # if ch is not found in cur that means word not presant so result is false
35+
return False
36+
cur = cur[ch] #if ch present then go till the end unless it becomes false
37+
if '*' in cur: # if * key not present that means words is prefix of a word that is present but word is not Present
38+
return True
39+
else:
40+
return False
41+
# dynamic input
42+
n2 = int(input("No of words to be Added:\n"))
43+
print("enter words:")
44+
words = []
45+
checks = []
46+
for j in range(n2):
47+
words.append(input())
48+
n3 = int(input("No of words to be searched:\n"))
49+
print("enter words:")
50+
for j in range(n3):
51+
checks.append(input())
52+
53+
54+
55+
"""
56+
Time complexity :
57+
Insert: O(word Length)
58+
Search: O(word Length)
59+
60+
Space complexity :
61+
Insert: O(1)
62+
Search: O(1)
63+
64+
Storages required for storing words:
65+
if no word has same prefix the required (total word length+1)*(char size)
66+
67+
"""
68+
dictionary = Trie() # Trie object created
69+
70+
71+
for k in words:
72+
dictionary.add(k) # adding word in Trie from words list
73+
for k in checks:
74+
print(dictionary.search(k)) # printing Searched word results if present then prints True if not present then returns False

0 commit comments

Comments
 (0)