Programs
Programs
Where Cob has written a script. Where the Script says double all the ascii values other than
mentioned in the bracket
(97,101,105,111,117,65,69,73,79,85) and place a '#' in between.
}
System.out.println(sb.toString());
}
public static boolean isSpecial(int ascii)
{
int special[] = {97, 101, 105, 111, 117, 65, 69, 73, 79, 85};
for(int i: special)
{
if(ascii==i)
return true;
}
return false;
}
}
DAY-2
//zigzag
import java.util.*;
class Solution{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
int n = sc.nextInt();
if(n<=1)
{
System.out.println(s);
return;
}
StringBuilder row[] = new StringBuilder[n];
for(int i=0;i<n;i++)
{
row[i] = new StringBuilder();
}
int r=0;
boolean down = false;
for(char c: s.toCharArray())
{
row[r].append(c);
if(r==0 || r==n-1)
down = !down;
r+= down ? +1:-1;
}
StringBuilder ans = new StringBuilder();
for(StringBuilder sr: row)
{
ans.append(sr);
}
System.out.println(ans.toString());
}
}
Gene and Minne are playing with the words. Minne is always sure that his word will be equal to the
Genes word, after moving few letters of the Genes word to the end.
Help Minne to solve the problem.
The first line of input contains the Genes word followed by Minne word.
If it matches print true else print false
Explanation -
After performing the Genes word abcdef bcdefa cdefab defabc efabcd fabcde
which doesnt match with the Minne word so the output is false
import java.util.*;
class Solution{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.next();
if(s1.equals(s2))
System.out.println("true");
if(s1.length()!=s2.length())
System.out.println("false");
if(s1.length()==s2.length()){
StringBuilder sb = new StringBuilder(s1);
boolean flag = true;
for(int i=0;i<s1.length();i++)
{
//String st = s1.substring(i) + s1.substring(0,i);
sb = sb.append(sb.charAt(0));
sb = sb.deleteCharAt(0);
if(s2.equals(sb.toString()))
{
flag = true;
break;
}
else
flag = false;
}
System.out.println(flag);
}
}
}
DAY-3
Rahul and Rohith are playing a switch game.
Rahul has given a string PresentState that contains only '+' and '-' . Both take turns to switch two
consecutive "++" into "--" . The game ends when a person can no longer make a move, and therefore
the other person will be the winner.
Return all possible states of the string presentState after one valid move. You may return the answer
in any order.If there is no valid move, return an empty list [] .
Input Format:
-------------
Line-1: A string represents present state.
Output Format:
--------------
Array of strings of possible states.
Constraints:
Sample Input-1:
---------------
--++-
Sample Output-1:
----------------
[-----]
Explanation:
-------------
++ will be converted as --. Then game ends.
Sample Input-2:
---------------
--+++-++
Sample Output-2:
----------------
[----+-++, --+---++, --+++---]
import java.util.*;
class Solution{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String s=sc.next();
generateStates(s);
}
public static void generateStates(String s){
List<String>list=new ArrayList<>();
StringBuilder sb=new StringBuilder(s);
for(int i=0;i<sb.length()-1;i++){
if(sb.charAt(i)=='+' && sb.charAt(i+1)=='+'){
sb.setCharAt(i,'-');
sb.setCharAt(i+1,'-');
list.add(sb.toString());
sb.setCharAt(i,'+');
sb.setCharAt(i+1,'+');
}
}
System.out.println(list);
A word will be given, where Ramu has to replace the letters of the word with V/C
If the letter is a vowel it will be de denoted by upper case letter ‘V’ and
if the letter is a consonant it will be denoted by upper case letter ‘C’.
Note - The output will contain a word containing alternating sequence of ‘C’ and ‘V’.
It is not permissible to have two or more consecutive V or C in Sequence.
Letters will be only(a-z/A-Z)
input = hello
output = CVCV
The first line of input contains the group size followed by group numbers followed by k
input = 5
1 5 3 2 10
3
output = 60
input = 7
8718291
2
output = 56
import java.util.*;
class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++)
{
arr[i] = sc.nextInt();
}
int k = sc.nextInt();
maxSum(arr,n,k);
}
public static void maxSum(int arr[],int n,int k)
{
if(k>n)
{
System.out.println("-1");
return;
}
long mSum = 1;
for(int i=0;i<k;i++)
{
mSum*=arr[i];
}
long wSum = mSum;
for(int i=k;i<n;i++)
{
wSum*=arr[i];
wSum/=arr[i-k];
mSum = Math.max(mSum,wSum);
}
System.out.println(mSum);
}
}
DAY_4
Mr. Param is working with Strings.
He is given a String S. He has to find the palindromes in S,
A palindrome can be a substring of S (Strictly substrings only, not subsequences).
Your task is to find the count the number of palindromes can be formed from S.
Input Format:
-------------
A string S
Output Format:
--------------
Print an integer, number of palindromes.
Sample Input-1:
---------------
divider
Sample Output-1:
----------------
9
Explanation:
-------------
Palindromes are d, i, v, i, d, e, r, ivi, divid
Sample Input-2:
---------------
abcdef
Sample Output-2:
----------------
6
Explanation:
-------------
Palindromes are a, b, c, d, e, f.
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String S=sc.nextLine();
System.out.println(countPalin(S));
}
public static int countPalin(String S){
List<String> palindrome=new ArrayList<>();
for(int i=0;i<S.length();i++){
for(int j=i+1;j<=S.length();j++){
String substr=S.substring(i,j);
if(isPalindrome(substr)){
palindrome.add(substr);
}
}
}
return palindrome.size();
}
public static boolean isPalindrome(String S){
int left=0;
int right=S.length()-1;
while(left<right){
if(S.charAt(left)!=S.charAt(right)){
return false;
}
left++;
right--;
}
return true;
}
}
Christina has given a task to break his friends code
he will given all lower case alphabets and code as the input
Christina has to figure the text from the code and display the text
Input - The first line of input consists of lower case alphabets and code
The first alphabet letter will given 01, second alphabet will be given 02, and so on
Output - Break the code and display the string
Explantion -
From the above test case we have 'a' has '01', 'b' has '02', and finally 'z' has '26'
where each alphabet will be assigned a two digit number
and for the code 110525 the characters will be 11 as 'k', 05 as 'e' and 25 as 'y'
so the output is "key"
Explantion - From the above test case we have 'q' as '01' , 'p' as '02' and finally 'v' as '26'
and for the code 131013090521 we have the following code
13-s
10-y
13-s
09-t
05-e
21-m
import java.util.*;
public class Program{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String alphabets = scanner.next();
String code = scanner.next();
Map<String, Character> mapping = new HashMap<>();
for (int i = 0; i < 26; i++) {
String number = String.format("%02d", i + 1);
mapping.put(number, alphabets.charAt(i));
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < code.length(); i += 2) {
String number = code.substring(i, i + 2);
char character = mapping.get(number);
result.append(character);
}
System.out.println(result.toString());
}
}
DAY-5
A professional thief entered into a floor in a building,
The floor has M*N inter connected rooms, the thief can enter into any room
from any other room. And there are few rooms closed from inside, so the thief
cannot enter into them. Initially the thief is at room[0][0] and has to exit
from room[m-1][n-1].
Input Format:
-------------
Line-1: Two space separated integers, M and N.
Next M lines: N space separated integers, either 0 or 1.
Output Format:
--------------
Print an integer result.
Sample Input-1:
---------------
34
0000
0100
0010
Sample Output-1:
----------------
2
Sample Input-2:
---------------
44
0000
0010
1000
0010
Sample Output-2:
----------------
3
import java.util.Scanner;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int room[][]=new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
room[i][j]=sc.nextInt();
}
}
System.out.print(directions(m,n,room));
}
public static int directions(int m,int n,int[][] room){
int dp[][]=new int[m][n];
dp[0][0]=1;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(dp[i][j]==1){
continue;
}
if(i>0&&room[i-1][j]==0){
dp[i][j]+=dp[i-1][j];
}
if(j>0&&room[i][j-1]==0){
dp[i][j]+=dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
}
Scott is a sweet lover and eats sweets daily. His father is worried about his health
and gives a task to Scott. If Scott solves the task then he is allowed to eat the sweets.
Scott is given a word 'W'. Now he is supposed to see, the word is a Balanced Word or Not .
A word is said to be Balanced word if it contains all characters same number of times.
He can also make the word Balanced by removing only one occurence of a character at any index in
the word.
input = xyz
output = true
input = xxyyzzzz
output = false
input = xzxyzxz
output = true
import java.util.HashMap;
import java.util.Map;
Day 6
/////////////
A string is good if there are no repeated characters.
Note that if there are multiple occurrences of the same substring, every occurrence should be
counted.
input =xyzzaz
output =1
Explanation:
There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz".
The only good substring of length 3 is "xyz".
input =aababcabc
output = 4
Explanation:
There are 7 substrings of size 3:
"aab", "aba", "bab", "abc", "bca", "cab", and "abc".
The good substrings are "abc", "bca", "cab", and "abc".
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String input=sc.next();
System.out.println(countsubstr(input));
}
public static int countsubstr(String input){
int count=0;
for(int i=0;i<input.length()-2;i++){
String substr=input.substring(i,i+3);
if(Goodsubstr(substr)){
count++;
}
}
return count;
}
public static boolean Goodsubstr(String input){
HashSet<Character> set=new HashSet<>();
for(char ch:input.toCharArray()){
if(!set.add(ch)){
return false;
}
}
return true;
}
}
You are given a list of N integers List[], list contains both +ve and -ve integers.
Your task is to findout, the Highest Product possible,
Where the product is the product of all the elements of contiguous sublist sList[],
and sub list should conatin atleast 1 integer.
Input Format:
-------------
Line-1: An integer N.
Line-2: N space separated integers, List[].
Output Format:
--------------
Print an integer output, the highest product.
Sample Input-1:
---------------
4
2 3 -2 4
Sample Output-1:
----------------
6
Explanation:
------------
Product of contiguous sub list [2,3].
Sample Input-2:
---------------
3
-2 0 -3
Sample Output-2:
----------------
0
Explanation:
------------
Product of sub list [0], where [-2,-3] is not a contiguous sublist
import java.util.*;
class HighestProduct{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int list[]=new int[n];
for(int i=0;i<n;i++){
list[i]=sc.nextInt();
}
System.out.println(MaxProduct(list,n));
}
public static int MaxProduct(int list[], int n) {
int maxprod = list[0];
int minprod = list[0];
int maxsofar = list[0];
int max=list[0];
int min=list[0];
int res=min;
for(int i=1;i<n;i++){
int x=list[i];
int max1=max*x;
int min1=min*x;
min=Math.min(x,Math.min(max1,min1));
max=Math.max(x,Math.max(max1,min1));
res=Math.max(res,max);
}
return res;
}
}
Day 7
In a shopping mall, there is a Lift with a capacity of 500kgs only.
There are N persons waiting for the lift, and their weights (weights[]) are given.
If The Lift is overloaded, it will not move.
Your task is to find out the maximum number of persons can use the Lift,
without any overloading issue.
Input Format:
-------------
Line-1: An integer N, number of persons
Line-2: N space separated integers, weights of the persons.
Output Format:
--------------
Print an integer, max num of persons canuse the lift.
Sample Input-1:
---------------
6
98 121 76 135 142 65
Sample Output-1:
----------------
5
Sample Input-2:
---------------
7
85 67 69 83 54 61 50
Sample Output-2:
----------------
7
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int weights[]=new int[n];
for(int i=0;i<n;i++){
weights[i]=sc.nextInt();
}
Arrays.sort(weights);
System.out.println(maxpersons(weights,n));
}
public static int maxpersons(int weights[],int n){
int count=0,total_weight=0;;
for(int i=0;i<n;i++){
total_weight+=weights[i];
if(total_weight<=500){
count++;
}
}
return count;
}
}
Rahul is given a row of numbers where each row and columns are same.
Rahul now prints the numbers of the rows as shown in the following manner.
Help Rahul to write the code .
The first line of input consists of the size followed by the row numbers.
Sample Input:
3
123
456
789
Explanation:
1<-2<-3
4->5->6
7<-8<-9
Sample Output:
321456987
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int matrix[][]=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
matrix[i][j]=sc.nextInt();
}
}
for(int i=0;i<n;i++){
if(i%2==0){
for(int j=n-1;j>=0;j--){
System.out.print(matrix[i][j]+" ");
}
}
else{
for(int j=0;j<n;j++){
System.out.print(matrix[i][j]+" ");
}
}
}
}
}
Bob Khan is working with various number systems.
He has created two kinds of addressing systems to share information
between any two electronic devices.
Input Format:
-------------
A string, an address addr.
Output Format:
--------------
Print a string output, as mentioned in above statement.
Sample Input-1:
---------------
213.234.45.12
Sample Output-1:
----------------
Type-I
Sample Input-2:
---------------
abcd:ef12:3456:7:dce8:fab9:1:0cda
Sample Output-2:
----------------
Type-II
Sample Input-3:
---------------
abcd:ef12:3456:7:0dce8:fab9:1:0cda
Sample Output-3:
----------------
Invalid
Sample Input-4:
---------------
[email protected]
Sample Output-4:
----------------
Invalid
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String input=sc.next();
if(input.contains(".")){
String[] octet=input.split(".");
if(octet.length!=4){
System.out.println("Invalid");
}
for(String c:octet){
if(!validoctet(c)){
System.out.println("Invalid");
}
}
System.out.println("Type I");
}
else if(input.contains(":")){
String[] hextet=input.split(":");
if(hextet.length!=8){
System.out.println("Invalid");
}
for(String h:hextet){
if(!validhextet(h)){
System.out.println("Invalid");
}
}
System.out.println("Type II");
}
else{
System.out.println("Invalid");
}
}
public static boolean validoctet(String octet){
try {
int num = Integer.parseInt(octet);
return !(octet.startsWith("0") && octet.length() > 1) && num >= 0 && num <= 255;
} catch (NumberFormatException e) {
return false;
}
}
public static boolean validhextet(String hextet){
return hextet.matches("[0-9a-fA-F]{1,4}");
}
}
Day 8
1 2 3
abc def
4 5 6
ghi jkl mno
7 8 9
pqrs tuv wxyz
* 0 #
Input Format:
-------------
String(2-9)
Output Format:
--------------
Print the list of words in alphabetical order
Sample Input-1:
---------------
2
Sample Output-1:
----------------
abc
Sample Input-2:
---------------
24
Sample Output-2:
----------------
ag ah ai bg bh bi cg ch ci
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String S=sc.next();
List<String> result=generateWords(S);
for(String c:result){
System.out.print(c+" ");
}
}
private static final Map<Character,String>mapping=new HashMap<>();
static{
mapping.put('2',"abc");
mapping.put('3',"def");
mapping.put('4',"ghi");
mapping.put('5',"jkl");
mapping.put('6',"mno");
mapping.put('7',"pqrs");
mapping.put('8',"tuv");
mapping.put('9',"wxyz");
}
private static List<String> generateWords(String S) {
List<String> result = new ArrayList<>();
generateWordsHelper(S, 0, "", result);
return result;
}
private static void generateWordsHelper(String S,int index,String current,List<String> result) {
if (index==S.length()) {
result.add(current);
return;
}
char digit=S.charAt(index);
String letters=mapping.get(digit);
for(char letter:letters.toCharArray()){
generateWordsHelper(S,index+1,current+letter,result);
}
}
}
Steve is Designing a New email system.Where he wants to eliminate the gmail of based on few
conditions.
Every valid email consists of a local name and a domain name, in between '@';
For example, in "[email protected]" , "alice" is the local name, and "gmail.com" is the domain name.
Besides lowercase letters, the email may contain one or more '.' or '+' .
If you add period '.' between some characters in the local name part of an email address, mail sent
there will be forwarded to
the same address without dots in the local name.
For example, "[email protected]" and "[email protected]" forward to the same email address.
If you add a plus '+' in the local name, everything after the first plus sign will be ignored.
This allows certain emails to be eliminated.
This rule will not be applicable to to domain names.
Example 2:
Input: emails = ["[email protected]","[email protected]","[email protected]"]
Output: 3
DAY_9
Kalpana a third class student is playing with numbers.
She has given her brother the same set of numbers and asked him to find the
next greatest nearest number which contains the same set of digits same number of times.
input = 121
output = 211
input = 653
output = -1
input = 456
output = 465
import java.util.*;
class Program{
static int function(int n)
{
char arr[]=String.valueOf(n).toCharArray();
int pivot=-1;
for(int i=arr.length-2;i>=0;i--){
if(arr[i]<arr[i+1])
{
pivot=i;
break;
}
}
if(pivot==-1)
{
return -1;
}
int successor=-1;
for(int i=arr.length-1;i>=0;i--)
{
if(arr[i]>arr[pivot])
{
successor=i;
break;
}
}
char temp=arr[pivot];
arr[pivot]=arr[successor];
arr[successor]=temp;
Arrays.sort(arr,pivot+1,arr.length);
int res=Integer.parseInt(new String(arr));
return res;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.print(function(n));
}
}
Assume the relations here limit only to child and grandChild only
all the inputs will be given in lower case characters(a-z) and are valid relations
the first line of input consists of number of relations followed by child name and fathers name
seperated by ','
followed by a name.
input =
5
kishore,ramesh
dev,gopal
gopal,ramu
srinu,gopal
praveen,ranjit
ramu
output = 2
example:2
input =
5
ranjit,knr
ramesh,pradeep
kittu,ranjit
yogesh,ranjit
praveen,ranjit
knr
output=
3
//given data for knr we need print the count of grand children .
here knr direct child is ranjit and ranjit has three children ---- kittu,yogesh,praveen so print 3
input =
8
a,b
c,b
d,b
f,a
g,a
e,a
m,c
z,d
b
output =
5
import java.util.*;
class test{
static int function(int n, HashMap<String,String> hm,String q){
if(hm.isEmpty())
{
return -1;
}
if(!hm.containsValue(q))
{
return -1;
}
ArrayList<String> al=new ArrayList<>();
for(Map.Entry<String,String> entry:hm.entrySet()){
if(entry.getValue().equals(q))
{
al.add(entry.getKey());
}
}
int count=0;
for(int i=0;i<al.size();i++){
for(Map.Entry<String,String> entry:hm.entrySet()){
if(entry.getValue().equals(al.get(i)))
{
count++;
}
}
}
if(count==0)
{
return al.size();
}
return count;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<String,String> hm=new HashMap<>();
for(int i=0;i<n;i++){
String s=sc.next();
String st[]=s.split(",");
hm.put(st[0],st[1]);
}
String q=sc.next();
System.out.print(function(n,hm,q));
}
}
DAY 10
Given an matrix with no duplicate values, return all lucky numbers in the
matrix.
A lucky number is an element of the matrix such that, it is the maximum element in its row and
minimum in its column.
ex:
input =
33
378
9 11 13
15 16 17
output =8
explanantion: 8 is the only lucky number since it is the maximum number in row and minimum in its
column.
ex2:
input =
3
4
15 16 17 12
9387
1 10 4 2
output =-1
none of the elements in the matrix matches the luckynumber rules. so print -1.
input =
22
12
78
output =2
explanantion: 2 is the only lucky number since it is the maximum number in row and minimum in its
column.
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int matrix[][]=new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
matrix[i][j]=sc.nextInt();
}
}
System.out.println(LuckyNum(matrix,m,n));
}
public static int LuckyNum(int matrix[][],int m,int n){
int rowmax=Integer.MIN_VALUE;
int ind=0;
for(int i=0;i<m;i++){
if(matrix[0][i]>rowmax){
rowmax=matrix[0][i];
ind=i;
}
}
int colmin=Integer.MAX_VALUE;
for(int j=0;j<m;j++){
colmin=Math.min(matrix[j][ind],colmin);
}
if(rowmax==colmin){
return colmin;
}
return -1;
}
}
• If T < lower, they performed poorly on their diet and lose 1 point;
• If T > upper, they performed well on their diet and gain 1 point;
• Otherwise, they performed normally and there is no change in points.
Initially, the dieter has zero points. Return the total number of points the dieter has after
dieting for calories.length days.
Note that the total points can be negative.
Example 1:
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
Output: 0
Explanation: Since k = 1, we consider each element of the array separately and compare it to
lower and upper.
calories[0] and calories[1] are less than lower so 2 points are lost.
calories[3] and calories[4] are greater than upper so 2 points are gained.
Example 2:
Input: calories = [3,2], k = 2, lower = 0, upper = 1
Output: 1
Example 3:
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
Output: 0
Explanation:
calories[0] + calories[1] > upper so 1 point is gained.
lower <= calories[1] + calories[2] <= upper so no change in points.
calories[2] + calories[3] < lower so 1 point is lost
Constraints:
• 1 <= k <= calories.length <= 10^5
• 0 <= calories[i] <= 20000
• 0 <= lower <= upper
import java.util.Scanner;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] calories=new int[n];
for(int i=0;i<n;i++){
calories[i]=sc.nextInt();
}
int k=sc.nextInt();
int lower=sc.nextInt();
int upper=sc.nextInt();
System.out.println(TotPoints(calories,n,k,upper,lower));
}
public static int TotPoints(int[] calories,int n,int k,int upper,int lower){
int points=0;
int sum=0;
for(int i=0;i<k;i++){
sum+=calories[i];
}
if(sum>upper){
points++;
}
else if(sum<lower){
points--;
}
for(int i=k;i<n;i++){
sum+=calories[i];
sum-=calories[i-k];
if(sum>upper){
points++;
}
else if(sum<lower){
points--;
}
}
return points;
}
}
Given an integer array nums and an integer k, you are asked to construct the array ans of
size n-k+1 where ans[i] is the number of distinct numbers in the subarray nums[i:i+k-1] =
[nums[i], nums[i+1], ..., nums[i+k-1]].
Return the array ans.
Example 1:
Input: nums = [1,2,3,2,2,1,3], k = 3
Output: [3,2,2,2,3]
Explanation: The number of distinct elements in each subarray goes as follows:
- nums[0:2] = [1,2,3] so ans[0] = 3
- nums[1:3] = [2,3,2] so ans[1] = 2
- nums[2:4] = [3,2,2] so ans[2] = 2
- nums[3:5] = [2,2,1] so ans[3] = 2
- nums[4:6] = [2,1,3] so ans[4] = 3
Example 2:
Input: nums = [1,1,1,1,2,3,4], k = 4
Output: [1,2,3,4]
Explanation: The number of distinct elements in each subarray goes as follows:
- nums[0:3] = [1,1,1,1] so ans[0] = 1
- nums[1:4] = [1,1,1,2] so ans[1] = 2
- nums[2:5] = [1,1,2,3] so ans[2] = 3
- nums[3:6] = [1,2,3,4] so ans[3] = 4
Constraints:
• 1 <= k <= nums.length <= 105
• 1 <= nums[i] <= 10
import java.util.*;
class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int nums[]=new int[n];
for(int i=0;i<n;i++){
nums[i]=sc.nextInt();
}
for(int i=0;i<n-k+1;i++){
Set<Integer> hs=new HashSet<>();
for(int j=0;j<k;j++){
hs.add(nums[i+j]);
}
System.out.print(hs.size()+" ");
}
}
}
Tinku a Small Kid is playing with the Amazon Fire TV Stick Remote
Tinku is not familar with the alphabets.
He father gives him few alphabets and asks Tinku to type it.
Tinku uses only one finger.
At the Beginining, he will put his finger at the the 1st key, k[0];
To type the Next Alphabet he has to move his finger from that key(m)
to that particular alphabet(n) he takes |m-n| seconds.
Help Tinkus Father to see how much seconds does Tinku take to type the given alphabets.
input=poiuytrewqasdfghjklmnbvcxz
kmit
output=39
input=abcdefghijklmnopqrstuvwxyz
code
output=26
import java.util.*;
class Solution{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String s=sc.next();
String word=sc.next();
int sum=s.indexOf(word.charAt(0));
for(int i=0;i<word.length()-1;i++){
sum+=Math.abs(s.indexOf(word.charAt(i))-s.indexOf(word.charAt(i+1)));
}
System.out.println(sum);
}
}