So i did solved the Compress Video Code, but when am implementing the logic it is not passinng 2 test cases, one of which has 6202 input and the correct output is 6201, whereas my output is 6202.
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n= sc.nextInt();
while(n-->0){
int t=sc.nextInt();
ArrayList<Integer> frames= new ArrayList<>();
while(t-->0){
int f=sc.nextInt();
frames.add(f);
}
compressVideo(frames);
}
}
public static void compressVideo(ArrayList<Integer> frames){
int count=1;
for(int i=0;i<frames.size()-1;i++){
if(frames.get(i) != frames.get(i+1)) count++;
}
System.out.println(count);
}
this is the code that I did, I can’t seem to find what the error is, I saw the solution and when I implement the same logic with array it works.
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int t1 = sc.nextInt();
while(t1-->0){
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i<n; i++) {
arr[i] = sc.nextInt();
}
int count = 1;
for(int i = 0; i<n-1; i++) {
if(arr[i] != arr[i+1]) count++;
}
System.out.println(count);
}
}
it is the exact same logic but you are using != to compare Integers.
If you want to compare values, you use == and != for primitive datatypes (char, int, long) - datatypes that start with a lowercase letter. But you have to use equals() and !equals() when comparing Objects (String, Integer, Long) - Object types that starts with an uppercase letter.
I tried to do the question using string/string builder. When I run the code all my custom input outputs correct answer but when I submit the same code it fails.
here is my code:
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0){
int n = scn.nextInt();
StringBuilder frame = new StringBuilder("");
for(int i = 0; i<n; i++){
frame.append(scn.next());
}
String frames = frame.toString();
int count = 1;
for(int i = 0; i< n-1; i++){
if(frames.charAt(i) != frames.charAt(i+1)){
// frames.delete(i,i+1);
count++;
}
}
System.out.println(count);
}
}
}
I tried the .equals method as well I couldn solcve the problem. Can you help
the fix is to not use Stringbuilder. It is not meant for these kinds of problems, you only use Stringbuilder if you need to build a String fast. You abused it to store data, though.
Here an example testcase that does not work:
Input:
Thank You, but here is a thing, I was studying Strings and String builder and I wanted to solve some questions on the same so I selected the String topic and this question popped up So even though I wanted to solve it usingsome other ds I thought there has to be something that I cant figure out about strings