Utilities :

Occurrence of each element


Problem Statement – ?Todo

//Using Map
HashMap<Character,Integer> occuranceCount=new HashMap<>();
for(int i=0;i<arr.length();i++){
occuranceCount.put(arr[i],occuranceCount.getOrDefault(arr[i],0)+1));
}

//without using additional DS



Convert character to lowerToUpperCase and vice-versa


//1- using magic number 32 
char a = 'a';
a -= 32;
System.out.println("a is " + a); //a is A
//2 binary operations
//2.1 lower to Upper use binary &
The binary AND operation: (l & 0x5f)
i.e System.out.println((char)('l' & 0x5f));
//2.1 Upper to lower use binary XOR ^
i.e System.out.println((char)(('L' ^ 0x20));

//3 using inbuilt function of Character class
char fUpper = Character.toUpperCase('f');
char lUpper = Character.toUpperCase('l')';

//How it works:
Binary, hex and decimal table:

------------------------------------------
| Binary   |   Hexadecimal     | Decimal |
-----------------------------------------
| 1011111  |    0x5f           |  95     |
------------------------------------------
| 100000   |    0x20           |  32     |
//Hints -ASCII codes
A-65, Z-90
a-97,z-122

Matrix -Properties


  1. Properties of Matrix [ N x N ]
  1. Major Diagonal Identification – rowNumber==colNUmber
    • i.e rowNumber and col number are same
  2. Minor Diagonal Identification – rowNumber+colNUmber=total size of Matrix
    • sum of rowNumber and col number is equal to total size of matrix

Bug Free Input in Java


Skip UNNECESSARY input:

After Input user presses <Enter> key which is not accepted by current input so, to avoid it being taken as input of next statement,Skip the special cases like newline(\n), line-separator (\u2028), paragraph separator (\u2029) etc.

int n = scanner.nextInt();        
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

Probable ArrayIndexOutOfBound -Graceful handling


Problem :

  • 2 staring arrays S1 -length 2 and S2 lenght – 3, so accessing the elements without AIOB-
  • Use case- LC -Version comparison

for(int i=0;i<maxLen;i++){
//here maxLen is bigger len i.e 3
int a1=i>s1.length?0:s1[i];

int a2=i>s2.length?0:s2[i];
//in above we checked length and returned compensatory rult -0 or actual
}

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment