0% found this document useful (0 votes)
30 views20 pages

String and Arrays

The document contains various Java programming questions and solutions related to string and array manipulations, including finding duplicates, reversing strings, checking for anagrams, counting vowels and consonants, and checking for palindromes. It also includes questions on matrix operations, such as calculating diagonal sums and flipping images, as well as problems related to password validation and calculating differences in sums based on divisibility. Each question is accompanied by a code snippet demonstrating the solution.

Uploaded by

giteshkumar.nmc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views20 pages

String and Arrays

The document contains various Java programming questions and solutions related to string and array manipulations, including finding duplicates, reversing strings, checking for anagrams, counting vowels and consonants, and checking for palindromes. It also includes questions on matrix operations, such as calculating diagonal sums and flipping images, as well as problems related to password validation and calculating differences in sums based on divisibility. Each question is accompanied by a code snippet demonstrating the solution.

Uploaded by

giteshkumar.nmc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

STRINGS

Ques. How to print duplicates characters from String?

public static void main(String[]args){

String str="javaj";
int[]farr=new int[128]; //freq arr to get the frequency of every character

for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
farr[ch]++;
}

ArrayList<Character>ans=new ArrayList<>(); // to store the answer


for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(farr[ch]>1){
ans.add(ch);
farr[ch]=-1; // taaki same character multiple times na add ho ans
arraylist main
}
}

System.out.println(ans);

Ques. How to Print duplicate characters from String ? (Space optimised


approach )

public static void main(String[]args){

String str="yoyosnehala";
int[]farr=new int[26]; //freq arr to get the frequency of every character

for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
farr[ch-'a']++;
}

ArrayList<Character>ans=new ArrayList<>(); // to store the answer


for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(farr[ch-'a']>1){
ans.add(ch);
farr[ch-'a']=-1; // taaki same character multiple times na add ho ans
arraylist main
}
}

System.out.println(ans);

Ques. You will be given a string str that only contains lowercase or
uppercase alphabets.You have to reverse the string

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
String str=scn.nextLine();

String ans="";
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
ans=ch+ans;
}
System.out.println(ans);
}

Ques. You will be given a string str that only contains lowercase or
uppercase alphabets.You have to reverse the string(Optimised approach)

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
String str=scn.nextLine();
StringBuilder sb=new StringBuilder();

for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
sb.insert(0,ch);
}
System.out.println(sb);
}

Ques. You are given a string str. You have to find the maximum occurring
character in the input string e.g if input string is "test" then function
should return 't'.

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
String str=scn.nextLine();

int[]farr=new int[26];
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
farr[ch-'a']++;
}

char maxc=str.charAt(0);
int maxfreq=farr[maxc-'a'];
for(int i=1;i<str.length();i++){
char ch=str.charAt(i);
if(farr[ch-'a']>maxfreq){
maxfreq=farr[ch-'a'];
maxc=ch;
}
}
System.out.println(maxc);

Ques. Check if two strings are anagrams or not

public static void main(String[]args){


String s1="triangle";
String s2="anglerit";

if(s1.length()!=s2.length()) {
System.out.println("false");
return;
}

int[]farr=new int[26];
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
farr[ch-'a']++;
}

for(int i=0;i<s2.length();i++){
char ch=s2.charAt(i);
farr[ch-'a']--;
if(farr[ch-'a']<0){
System.out.println("false");
return;
}
}
System.out.println("true");

Ques. How to program to print the first non repeated character from
String?

public static void main(String[]args){


String s1="yadavy";

int[]farr=new int[26];
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
farr[ch-'a']++;
}

for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
if(farr[ch-'a']==1){
System.out.println(ch);
return;
}
}
System.out.println("not a single character with frequency 1");
}

Ques. How to count a number of vowels and consonants in a String?

public static void main(String[]args){


String str="aeioubcd";
int vowelCount=0;
int consonantCount=0;
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
vowelCount++;
}else{
consonantCount++;
}
}
System.out.println(vowelCount +" "+ consonantCount);
}

Ques. Check if given string is palindrome or not?


public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str=scn.nextLine();
int i=0;
int j=str.length()-1;

while(i<j){
char ch1=str.charAt(i);
char ch2=str.charAt(j);
if(ch1!=ch2){
System.out.println("false");
return;
}
i++;
j--;
}
System.out.println("true");

Ques. Write a program to replace a given character with replacingCh from


String?

public static void main(String[]args){


String str="vinaypatel";
char givenCh='a' ; //the character you need to replace in string
char replacingCh='k'; //the character you need to replace in string with

StringBuilder sb=new StringBuilder();


for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(ch==givenCh){
sb.append(replacingCh);
}else{
sb.append(ch);
}
}
String ans=sb.toString();
System.out.println(ans);
}

Ques. Remove the given character from string


public static void main(String[]args){
String str="vinaypatel";
char givenCh='a' ; //the character you need to replace in string

StringBuilder sb=new StringBuilder();


for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(ch==givenCh){
//nothing to do
}else{
sb.append(ch);
}
}
String ans=sb.toString();
System.out.println(ans);
}

Ques. PANGRAM

A pangram is a sentence where every letter of the English alphabet appears


at least once.Given a string sentence containing only lowercase English
letters, return true if the sentence is a pangram, or false otherwise.
public boolean checkIfPangram(String sentence) {
int[]farr=new int[26];
for(int i=0;i<sentence.length();i++){
farr[sentence.charAt(i)-'a']++;
}
for(int i=0;i<farr.length;i++){
if(farr[i]==0) return false;
}
return true;
}

ARRAYS

Ques. Find duplicates in an array

public int findDuplicate(int[] nums) {

for(int i=0;i<nums.length;i++){
int val=Math.abs(nums[i]);
if(nums[val-1]<0){
return val;
}
nums[val-1]=-(nums[val-1]);
}
return -1;
}

Ques. There is an array with every element repeated twice except one. Find
that element?

public static void main(String[]args){


int[]arr={1,2,1,3,2,3,4,4,6};

int[]farr=new int[100]; //100->range of numbers that are in array


for(int i=0;i<arr.length;i++){
int val=arr[i];
farr[val]++;
}

for(int i=0;i<arr.length;i++){
int val=arr[i];
if(farr[val]==1){
System.out.println(val);
}
}

Ques. Leetcode 1662

Check If Two String Arrays are Equivalent

Given two string arrays word1 and word2, return true if the two arrays
represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in
order forms the string.
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]

Output: true

Explanation:

word1 represents string "ab" + "c" -> "abc"

word2 represents string "a" + "bc" -> "abc"

The strings are the same, so return true.

class Solution {

public boolean arrayStringsAreEqual(String[] word1, String[] word2) {

StringBuilder sb=new StringBuilder();

StringBuilder sb2=new StringBuilder();


for(int i=0;i<word1.length;i++){

sb.append(word1[i]);

for(int i=0;i<word2.length;i++){

sb2.append(word2[i]);

if(sb.length()!=sb2.length()) return false;

String s=sb.toString();

String s2=sb2.toString();

if(s.equals(s2)) return true;

else return false;

Ques. leetcode 1572

Matrix diagonal sum

Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all
the elements on the secondary diagonal that are not part of the primary
diagonal.

class Solution {
public int diagonalSum(int[][] mat) {
int c=0;
for(int i=0;i<mat.length;i++){
for(int j=0;j<mat[0].length;j++){
if(i==j || i+j==mat.length-1){
c+=mat[i][j];
}
}
}

return c;
}
}

Ques. Leetcode 832

Flipping an image

Given an n x n binary matrix image, flip the image horizontally, then invert
it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
● For example, flipping [1,1,0] horizontally results in [0,1,1].
To invert an image means that each 0 is replaced by 1, and each 1 is
replaced by 0.
● For example, inverting [0,1,1] results in [1,0,0].

class Solution {
public int[][] flipAndInvertImage(int[][] image) {

for(int p=0;p<image.length;p++){
int i=0;
int j=image[0].length-1;
while(i<j){
int temp=image[p][i];
image[p][i]=image[p][j];
image[p][j]=temp;
i++;
j--;
}
}
for(int []val:image){
for(int i=0;i<val.length;i++){
if(val[i]==0) val[i]=1;
else val[i]=0;
}
}
return image;
}
}

Ques. MAXIMUM SUBARRAY (LEETCODE 53)

public int maxSubArray(int[] nums) {


//kadane's algorithm
int overallsum=nums[0];
int runningsum=nums[0];

for(int i=1;i<nums.length;i++){
int val1=runningsum+nums[i];
int val2=nums[i];
runningsum=Math.max(val1,val2);

if(runningsum>overallsum){
overallsum=runningsum;
}
}
return overallsum;
}

Ques. LEETCODE 463


ISLAND PERIMETER

public static int islandPerimeter(int[][] grid) {

int onescount=0,nbrcount=0;
int[][]dir={{1,0},{-1,0},{0,1},{0,-1}};
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
onescount++;

for(int d=0;d<dir.length;d++){
int r=i+dir[d][0];
int c=j+dir[d][1];

if(r>=0 && c>=0 && r<grid.length && c<grid[0].length &&


grid[r][c]==1 ){
nbrcount++;
}
}
}
}
}
return 4*onescount-nbrcount;
}

Ques. Write a Java program to form the largest number from a given list of
non negative integers.

Example:
Input :
nums = {1, 2, 3, 0, 4, 6}
Output:
Largest number using the said array numbers: 643210

Ques. Write a Java program to replace each element of the array with a
product of every other element in a given array of integers.

Ques. You are given a function.


int CheckPassword(char str[], int n);

The function accepts string str of size n as an argument. Implement the function
which returns 1 if given string str is valid password else 0.

str is a valid password if it satisfies the below conditions.

● – At least 4 characters
● – At least one numeric digit
● – At Least one Capital Letter
● – Must not have space or slash (/)
● – Starting character must not be a number

Assumption:

Input string will not be empty.

Example:

Input:

aA1_67

Output:

Sample Input:

a987 abC012

Output:

Solution:
import java.util.*;
class Solution
{

public static int checkPassword (String str, int n)


{
if (n < 4)
return 0;
if (str.charAt (0) >= '0' && str.charAt (0) <= '9')
return 0;

int num = 0, cap = 0;


for (int i = 0; i < n; i++)
{
if (str.charAt (i) == ' ' || str.charAt (i) == '/')
return 0;
if (str.charAt (i) >= 'A' && str.charAt (i) <= 'Z')
cap++;
if (str.charAt (i) >= '0' && str.charAt (i) <= '9')
num++;
}
if (cap > 0 && num > 0)
return 1;
else
return 0;
}

public static void main (String[]args)


{
Scanner sc = new Scanner (System.in);
String str = sc.next ();
System.out.println (checkPassword (str, str.length ()));
}
}

Ques. def differenceofSum(n. m)

The function accepts two integers n, m as arguments Find the sum of all
numbers in range from 1 to m(both inclusive) that are not divisible by n. Return
difference between sum of integers not divisible by n with sum of numbers
divisible by n.

Assumption:
● n>0 and m>0
● Sum lies between integral range

Example

Input

n:4

m:20

Output

90

Explanation

● Sum of numbers divisible by 4 are 4 + 8 + 12 + 16 + 20 = 60


● Sum of numbers not divisible by 4 are 1 +2 + 3 + 5 + 6 + 7 + 9 + 10 + 11
+ 13 + 14 + 15 + 17 + 18 + 19 = 150
● Difference 150 – 60 = 90

Sample Input

n:3

m:10

Sample Output

19

Ques. The function accepts a string ‘ str’ of length n and two characters ‘ch1’
and ‘ch2’ as its arguments . Implement the function to modify and return the
string ‘ str’ in such a way that all occurrences of ‘ch1’ in original string are
replaced by ‘ch2’ and all occurrences of ‘ch2’ in original string are replaced by
‘ch1’.

Assumption: String Contains only lower-case alphabetical letters.

Note:

● Return null if string is null.


● If both characters are not present in string or both of them are same , then
return the string unchanged.
Example:

● Input:
○ Str: apples
○ ch1:a
○ ch2:p
● Output:
○ paales

Explanation:

‘A’ in original string is replaced with ‘p’ and ‘p’ in original string is replaced
with ‘a’, thus output is paales.

Ques. Union of Two arrays:

Given two arrays a[] and b[] of size n and m respectively. The task is to find
union between these two arrays.
Union of the two arrays can be defined as the set containing distinct elements
from both the arrays. If there are repetitions, then only one occurrence of the
element should be printed in the union.

Ques. Leetcode 1512

class Solution {

public int numIdenticalPairs(int[] nums) {

int c=0;

HashMap<Integer,Integer>map=new HashMap<>();

for(int i=0;i<nums.length;i++){

if(!map.containsKey(nums[i])){

map.put(nums[i],1);

}else{

c+=map.get(nums[i]);
map.put(nums[i],map.getOrDefault(nums[i],0)+1);

return c;

Ques. LEETCODE 1380(Saddle Price)

class Solution {

public List<Integer> luckyNumbers (int[][] matrix) {

List<Integer>ans=new ArrayList<>();

for(int r=0;r<matrix.length;r++){

int minincol=mincol(r,matrix);

int maxinrow=maxrow(minincol,matrix);

if(r==maxinrow){

ans.add(matrix[maxinrow][minincol]);

return ans;

public int mincol(int r,int[][]matrix){

int min=matrix[r][0];

int minc=0;

for(int i=1;i<matrix[0].length;i++){

if(matrix[r][i]<min){
min=matrix[r][i];

minc=i;

return minc;

public int maxrow(int c,int[][]matrix){

int max=matrix[0][c];

int maxr=0;

for(int i=1;i<matrix.length;i++){

if(matrix[i][c]>max){

max=matrix[i][c];

maxr=i;

return maxr;

Ques. LEETCODE 1

class Solution {

public int[] twoSum(int[] nums, int target) {

HashMap<Integer, Integer> map = new HashMap<>();

int[] ans = new int[2];


for(int i = 0; i < nums.length; i++){

if(map.containsKey(target - nums[i])){

ans[0] = map.get(target - nums[i]);

ans[1] = i;

break;

}else{

map.put(nums[i], i);

return ans;

Ques. Leetcode 1929

class Solution {

public int[] getConcatenation(int[] nums) {

int [] res = new int [2 * nums.length];

for(int i=0 ; i<nums.length ; i++)

res[i] = nums[i];

res[i + nums.length] = nums[i];

return res;

You might also like