Can some one help me to understand the time complexity for the below code. The program is for shifting all the zeros to the right of an array.
class TestClass {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String []s = br.readLine().split(" ");
int a[] = new int[s.length];
for(int i=0;i<s.length;i++)
a[i]=Integer.parseInt(s[i]);
int j= a.length-1;
int i=0;
while(j>=0 && i<a.length-1 && j-i>0){
if(a[i]==0){
while(a[j]==0)
j--;
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
i++;
}
for(int k:a)
System.out.print(k+" ");
}
}
Calculating time complexity will be difficult if we try to include the a[i]=Integer.parseInt(s[i]);since in Integer class , parseInt()method runs inside a while loop, and depending on the length of the passing String, it will gives different time complexity, but if we assume that it will take O(F(q)), the time complexity of your code will be O(s.length^2)+O((s.length)*O(F(q))
Related
Actually, I am doing an exercise from HackerEarth.
The exercise is pretty simple: I have to use a min-max algorithm but I have some struggles when I use the readLine method from the variable BufferReader.
I cannot figure out why but my min variable for an iteration keep the Integer.MAX_VALUE.
Code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int N = Integer.parseInt(br.readLine());
while (T-- >= 0) {
String[] line = br.readLine().trim().split("\\s");
int min = Integer.MAX_VALUE;
for (int i = 0; i < line.length - 1; i++) {
min = Math.min(min, Integer.parseInt(line[i]));
}
System.out.println(min);
}
}
}
Output
1
2147483647
2
I've made many corrections to your code.
You are not reading every N of every test case, you only read it once. You have to put it inside the while loop.
Method trim is unnecessary because inputs from the problems are always in the right manner.
Use > not >= when comparing using array lengths or the number of test cases, because it will iterate once more even if the index is already beyond the array's capacity or 0.
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-- > 0) {
br.readLine(); // to read N
String[] line = br.readLine().split(" ");
int min = Integer.MAX_VALUE;
for (int i = 0; i < line.length; i++) {
min = Math.min(min, Integer.parseInt(line[i]));
}
System.out.println(min);
}
}
So this is a question of gfg to find union of two arrays and following is my code:
class GFG {
public static void main (String[] args) {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
try{
int testcase = Integer.parseInt(buff.readLine());
while(testcase-->0) {
String[] input = buff.readLine().split(" ");
int size1 = Integer.parseInt(input[0]);
int size2 = Integer.parseInt(input[1]);
Set<Integer> set = new HashSet<>();
String[] inp1 = buff.readLine().split(" ");
String[] inp2 = buff.readLine().split(" ");
for(int i = 0; i < inp1.length; i++){
set.add(Integer.parseInt(inp1[i]));
}
for(int i = 0; i < inp2.length; i++){
set.add(Integer.parseInt(inp2[i]));
}
System.out.println(set.size());
}
}catch(IOException e){System.out.println(e);}
}
}
The expected time and auxiliary space complexity for this program is given as: O(N+M) where N and M are size of two arrays respectively.
So can anyone tell what is space complexity for above code.I am so confused about the space complexity for this code.
I'm a beginner and I want to output the following using a for loop and subscript and I'm not sure.
output:
Jamaica
amaica
maica
aica
ica
ca
a
What can I do, in order to achieve this output?
First: You need to loop for generating n line which is the length of array.
Second: You need to print the spaces with is same value as row - 1 number of times.
Second: You need to print character start from row - 1 number to the length of the string.
And the final solution will be:
public class MyClass {
public static void printStr(String str) {
int i,j;
for (i = 0; i < str.length();i++) {
for(j = 0; j < i; j++) {
System.out.print(" ");
}
for(j = i; j < str.length();j++) {
System.out.print(str.charAt(j));
}
System.out.println("");
}
}
public static void main(String args[]) {
MyClass.printStr("Jamaica");
}
}
I would use two regular expressions, the first to terminate the loop when the String is filled with white space. The second to replace the first non-white space character with a white space in the loop body (after printing the current String value). And, if it's possible the String might be empty you should guard against that. Like,
String s = "Jamaica";
if (!s.isEmpty()) {
while (!s.matches("\\s+")) {
System.out.println(s);
s = s.replaceFirst("\\S", " ");
}
}
Outputs (as requested)
Jamaica
amaica
maica
aica
ica
ca
a
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next(); //input through scanner class
int len = s.length();
for(int i=0;i<len;i++){
for(int j=0;j<i;j++){
System.out.print(" ");
}
for(int j=i;j<len;j++){
System.out.print(s.charAt(j));
}
System.out.println("");
}
}
Hopefully that helps
Try following code:
StringBuilder country = new StringBuilder("Jamaica");
for(int i=0; i< country.length();i++){
if(i > 0)
{
for(int j=0;j<i;j++){
country.setCharAt(j,' ');
}
}
System.out.println(country);
}
I participated in a coding challenge on hackerearth , and i was asked the following question .
Alice and Bob are playing a game in which Bob gives a string SS of length NN consisting of lowercase English alphabets to Alice and ask her to calculate the number of sub-strings of this string which contains exactly 3 vowels.
This is my code
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass1{
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
String stringArray[]=new String[N];
for (int i = 0; i < N; i++) {
int len = Integer.parseInt(br.readLine());
stringArray[i]=br.readLine();
}
for (int i = 0; i < N; i++) {
System.out.println(determineNumberOfSubstring(stringArray[i]));
}
}
public static int determineNumberOfSubstring(String str)
{
int numberOfSubstring=0;
for(int i=0;i<str.length();i++)
{
int ctr=0;
for(int j=1;j<str.length()-i;j++)
{
String subString = str.substring(i,i+j);
if(subString.length()<3)
{
continue;
}
if(subString.contains("a")||subString.contains("e")||subString.contains("i")||subString.contains("o")||subString.contains("u")
||subString.contains("A")||subString.contains("E")||subString.contains("I")||subString.contains("O")||subString.contains("U"))
{
ctr+=3;
}
}
if(ctr==3){
numberOfSubstring++;
}
}
return numberOfSubstring;
}
}
Iam getting time limit exceeded for the above code . Could any one help me out on how to optimise it .
Update1
Code as per #GhostCat logic , this needs to be tested and is not the final code.
class TestClass1{
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
String stringArray[]=new String[N];
for (int i = 0; i < N; i++) {
int len = Integer.parseInt(br.readLine());
stringArray[i]=br.readLine();
}
for (int i = 0; i < N; i++) {
System.out.println(determineNumberOfSubstring(stringArray[i]));
}
}
public static int determineNumberOfSubstring(String str)
{
int numberOfSubstring=0;
int ctr=0;
int subStringStart=0;
Stack<String> s = new Stack<String>();
for(int i=0;i<str.length();i++)
{
if(isVowel(str.charAt(i)))
ctr++;
if(ctr==3)
{
numberOfSubstring++;
ctr=0;
if(s.empty())
s.push(str.substring(0,i));
else
s.push(new String(s.peek().substring(1,i+1)));
i=str.indexOf(s.peek().charAt(1))-1;
}
}
return numberOfSubstring;
}
private static boolean isVowel(char c) {
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'
||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
return true;
return false;
}
}
Hint: your code is iterating the whole substring for each and any lower and upper case vowel there is. And that happens in a loop in a loop.
Instead: use ONE loop that goes over the characters of the input string. And then check each position if it is a vowel by checking against a set of characters (containing those valid vowels). The final thing you need: a simple "sliding" window; like: when you spot three vowels, you can increase your counter; to then "forget" about the first of the three vowels you just found; like in:
a x e y i --> vowels a/e/i give one substring
x e y i ... and you look out for the next substring e/i/... now
Actual implementation is left as exercise to the reader ...
Long story short: this count can be computed by processing your input ONCE. Your code is iterating countless times more than once. Well, not countless, but N * N * some more.
( the one thing to be careful with: when using a Set<Character> be precise when you turn a char value into aCharacter object; you want to minimize the instances of that happening, too; as that is a rather expensive operation )
HAPPY CODING ###### (if useful then upvote)
Que: count possible substring contain exactly 3 vowel in given string
my approach in O(n):
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
vector<long long int>idex;
idex.push_back(-1);
for(int i=0;i<n;i++)
{
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u')
{
idex.push_back(i);
}
}
idex.push_back(n);
if(idex.size()<5)
{
cout<<0<<endl;
}
else
{
long long int ans=0;
for(int i=1;i<=idex.size()-4;i++)
{
ans+=(idex[i]-idex[i-1])*(idex[i+3]-idex[i+2]);
}
cout<<ans<<endl;
}
}
I tried sorting strings using bubblesort, but I dont know whether it makes any sense but can someone just help me figure out how to sort strings and let me know if my logic is correct? i have converted the strings to character just to check if they are in alphabetical order..eg app ban acc will be sorted to acc app and ban..can anyone give the logic to this problem.
import java.io.*;
import java.util.*;
class sort
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the strings");
String str=br.readLine();
StringTokenizer st=new StringTokenizer(str,",");
String s1=st.nextToken();
String s2=st.nextToken();
String s3=st.nextToken();
char ch1[]=s1.toCharArray();
char ch2[]=s2.toCharArray();
char ch3[]=s3.toCharArray();
if ((ch1[0]<ch2[0])&&(ch1[0]<ch3[0])&&(ch2[0]<ch3[0]))
for(int i=0;i<4;i++)
{
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
System.out.println(+ch3[i]);
}
else if((ch2[0]<ch1[0]&&ch2[0]<ch3[0]&&ch1[0]<ch3[0]) )
for(int i=0;i<4;i++)
{
System.out.println(+ch2[i]);
System.out.println(+ch1[i]);
System.out.println(+ch3[i]);
}
else if((ch3[0]<ch1[0])&&(ch3[0]<ch2[0])&&ch1[0]<ch2[0])
for(int i=0;i<4;i++)
{
System.out.println(+ch3[i]);
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
}
}
}
Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better. Wikipedia
The following is the sort-cut way to do so.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");//your sentence will be split into words.
Arrays.sort(strArr);
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
If you wish, you can apply your own logic as follows.
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");
String temp;
for(int i = 0; i<strArr.length - 1; i++)
{
for(int j = 0; j<strArr.length - 1; j++)
{
if(strArr[j].compareTo(strArr[j+1]) > 0)
{
temp = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = temp;
}
}
}
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
In both the cases, I have assumed spaces as word separator and not commas , that you're using in your example.
First you need to choose how do you want to sort strings ?
is it by length ? is it by alpha order ?
After you choose the appropriated method, you just need to sync it for the existing sorting method of bubblesort.
public static int[] bubble(String[] str_arr) {
for (int i = 0, temp; i < str_arr.length-1; i++) {
for(int j = 0; j < str_arr.length-1; j++) {
if (str_arr[j] < str_arr[j+1]) {
temp = str_arr[j];
str_arr[j] = str_arr[j+1];
str_arr[j+1] = temp;
}
}
}
return str_arr;
}
As i mentions theres couple of ways of comparing strings:
Length - length of a string
Lexicographically - explanation here
If we want to use one of the two method mentioned above, we should change the line:
if (str_arr[j] < str_arr[j+1])
to
if (str_arr[j].length < str_arr[j+1].length)
Or for the lexicographically order we will use:
if (str_arr[j].compareTo(str_arr[j+1].length) < 0)
compareTo is a java String method that checking lexicog.. order.
it returnes:
0 - strings are identical.
positive number - first string is bigger then second string.
negative number - first string is smaller then second string.
String implements interface Comparable (so overrides compareTo() method), thus you can compare two strings (>,<,>=,<=). That's why you don't have to compare every char element by element. Not worth trying even.
The solution: put Strings into array:
String[] stringArray = new String[]{"element1","element2"};
and then use default bubble-sort algorithm:
for (int x = 1; x < stringArray.length; x++) {
for (int y = 0; y < stringArray.length - x; y++) {
if (stringArray[y].compareTo(stringArray[y + 1]) > 0) {
temp = stringArray[y];
stringArray[y] = stringArray[y + 1];
stringArray[y + 1] = temp;
}
}
}
and you should receive sorted array.