# TCS NQT Valid String Coding Question With Solution

TCS NQT Valid String Coding Question With Solution

We at gradjobopenings.com provide free job alerts of freshers job drives. In this website we list on campus job openings for freshers and off campus job openings for freshers and also work from home job openings. This is the best website to apply for off campus drive in India. Visit our website for government job alerts and private job alerts. We also list free interview notes and study materials, one of the best interview study website.comfortable to face the interviews:

Problem statement

Given a variable-length string S(input consisting) of ‘*’ and ‘#’, the task is to find the minimum number of ‘*’ or ‘#’ to make it a valid string. The string is considered to be valid if the number of ‘*’ and ‘#’ are equal. The ‘*’ and ‘#’ can be at any position in the string.

Note: The output will be a positive or negative integer based on the number of ‘*’ and ‘#’ in the input string.

– (* > #): positive integer

– (# > *): negative integer

– (# = *): 0

Input format  :

– First line: Input string, S

Output format  :

– First line: A single integer as described in the question

Constraints:

– 1 <= |S| <= 10^5

Examples

– Input: ### ***

– Output: 0

– Explanation: Number of * and # are equal

– Input: ###**

– Output: -1

– Input: #**

– Output: 1

Program in C

``````#include <stdio.h>

int main() {
char string[100000];
scanf("%s", string);
int asterisk = 0, hash = 0;
for (unsigned int i = 0 ; string[i] != '\0'; i++) {
if (string[i] == '*')
asterisk ++;
else if (string[i] == '#')
hash++;
}
printf("%d", asterisk - hash);
return 0;
}
``````

Program in C++

``````#include <iostream>

int main() {
int asterisk{0}, hash {0};
std::string str;
std::cin >> str;
for (auto i: str) {
if (i == '*')
asterisk++;
else if (i == '#')
hash++;
}
std::cout << asterisk - hash;
return 0;
}
``````

Program in Python

``````if __name__ == "__main__":
string = input()
asterisk = 0
hash = 0
for i in string:
if i == '*':
asterisk += 1
elif i == '#':
hash += 1
print(asterisk - hash, end = "")
``````

Program in Java

``````import java.util.Scanner;

class Main {
public static void main (String args[]) {
int asterisk = 0;
int hash = 0;
Scanner in = new Scanner(System.in);
String str = in.next();
in.close();
for (char ch: str.toCharArray()) {
if (ch == '*')
asterisk++;
else if (ch == '#')
hash++;
}
System.out.print(asterisk - hash);
}
}``````