Nitin Agrawal
Contact -
  • Home
  • Interviews
    • Secret Receipe
    • InterviewFacts
    • Resume Thoughts
    • Daily Coding Problems
    • BigShyft
    • Companies
    • Interviews Theory
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems >
        • Problem10
        • Problem300
      • AnagramsSet
    • Core Java >
      • Codility
      • Program Arguments OR VM arguments & Environment variables
      • Java Releases >
        • Java8 >
          • Performance
          • NasHorn
          • WordCount
          • Thoughts
        • Java9 >
          • ServiceLoaders
          • Lambdas
          • List Of Objects
          • Code Snippets
        • Java14 >
          • Teeing
          • Pattern
          • Semaphores
        • Java17 >
          • Switches
          • FunctionalStreams
          • Predicate
          • Consumer_Supplier
          • Collectors in Java
        • Java21 >
          • Un-named Class
          • Virtual Threads
          • Structured Concurrency
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
        • Future Or CompletableFuture
      • Important Points
      • Immutability
      • Dictionary
      • Sample Code Part 1 >
        • PatternLength
        • Serialization >
          • Kryo2
          • JAXB/XSD
          • XStream
        • MongoDB
        • Strings >
          • Reverse the String
          • Reverse the String in n/2 complexity
          • StringEditor
          • Reversing String
          • String Puzzle
          • Knuth Morris Pratt
          • Unique characters
          • Top N most occurring characters
          • Longest Common Subsequence
          • Longest Common Substring
        • New methods in Collections
        • MethodReferences
        • Complex Objects Comparator >
          • Performance
        • NIO >
          • NIO 2nd Sample
        • Date Converter
        • Minimum cost path
        • Find File
      • URL Validator
    • Julia
    • Python >
      • Decorators
      • String Formatting
      • Generators_Threads
      • JustLikeThat
    • Go >
      • Tutorial
      • CodeSnippet
      • Go Routine_Channel
      • Suggestions
    • Methodologies & Design Patterns >
      • Design Principles
      • Design Patterns >
        • TemplatePattern
        • Adapter Design Pattern
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • Singleton >
          • Singletons
        • Strategy
  • Frameworks
    • Apache Velocity
    • React Library >
      • Tutorial
    • Spring >
      • Spring Boot >
        • CustomProperties
        • ExceptionHandling
        • Custom Beans
        • Issues
      • Quick View
    • Rest WebServices >
      • Interviews
      • Swagger
    • Cloudera BigData >
      • Ques_Ans
      • Hive
      • Apache Spark >
        • ApacheSpark Installation
        • SparkCode
        • Sample1
        • DataFrames
        • RDDs
        • SparkStreaming
        • SparkFiles
    • Integration >
      • Apache Camel
    • Testing Frameworks >
      • JUnit >
        • JUnit Runners
      • EasyMock
      • Mockito >
        • Page 2
      • TestNG
    • Blockchain >
      • Ethereum Smart Contract
      • Blockchain Java Example
    • Microservices >
      • Messaging Formats
      • Design Patterns
    • AWS >
      • Honeycode
    • Dockers >
      • GitBash
      • Issues
      • Kubernetes
  • Databases
    • MySql
    • Oracle >
      • Interview1
      • SQL Queries
    • Elastic Search
  • Random issues
    • TOAD issue
    • Architect's suggestions
  • Your Views
import java.util.HashSet;

/**
 * Class to find the duplicate elements in a given matrix.
 * @author Nitin
 *
 */
public class Duplicates {

 public static void main(String[] args) {
  String[][] matrix = {{"1","apple","1","2"}, {"2","ball","1","ball"}, {"3","c","d","apple"}};
  System.out.println(findDuplicates(matrix));
 }

 /**
  * Below method uses hashcode defined for String class.
  * @param matrix
  * @return - Number of duplicates else -1 for exception condition
  */
 static int findDuplicates(String[][] matrix) {
  try {
   int rows = matrix.length;
   int cols = matrix[0].length;
   String[] vals = new String[1000000];
   String[] dup = new String[1000000];
   for(int i = 0; i < rows; i++) {
    for(int j = 0; j < cols; j++) {
     int temp = matrix[i][j].hashCode();
     int pos = temp%1000000;
     if(vals[pos] == null) {
      vals[pos] = matrix[i][j];
     } else {
      dup[pos] = matrix[i][j];
     }
    }
   }
   int count = 0;
   for(String str : dup) {
    if(str != null) {
     count++;
    }
   }
   return count;
  } catch(Exception e) {
   return -1;
  }
 }

 /**
  * Below method uses hashset to find the duplicates. Below way is memory efficient, as above one wastes a lot of memory
  * and thats also not sure if number of strings increase, will give correct answer.
  * @param matrix
  * @return - Number of duplicates else -1 for exception condition
  */
 static int findDuplicatesHash(String[][] matrix) {
  try {
   int rows = matrix.length;
   int cols = matrix[0].length;
   HashSet<String> hs = new HashSet<>();
   HashSet<String> result = new HashSet<>();
   for(int i = 0; i < rows; i++) {
    for(int j = 0; j < cols; j++) {
     if(!hs.add(matrix[i][j])) {
      result.add(matrix[i][j]);
     }
    }
   }
   return result.size();
  } catch(Exception e) {
   return -1;
  }
 }
}


/**
 * Encrypt/Decrypt the given message as per the given key as per the below conditions.
 * If operation value is 1 then encrypt the given message as per the key given, such that repeat the character
 * number of times as given in the key e.g. repeat 1st character 1 time, 2nd character 2 times and so on.
 * Same way if operation value is 2 then decrypt the message as per the key & key will tell which character is repeating
 * how many times in message. In case of any exception value will be -1. Output of below code is correct for given inputs.
 * @author Nitin
 *
 */
public class Message {
 public static void main(String[] args) {
  System.out.println(secureChannel(1, "Open", "12324"));
  System.out.println(secureChannel(2, "Oppeeennnn", "12324"));
 }

 static String secureChannel(int operation, String message, String key) {
  String result = null;
  if(message == null || message.length() == 0)
   return "-1";
  try {
   if(operation == 1) {
    StringBuilder sb = new StringBuilder();
    int len = message.length();
    int count = 0;
    for(char ch : key.toCharArray()) {
     int k = Character.getNumericValue(ch);
     if(count > len-1)
      break;
     while(k > 0) {
      sb.append(message.charAt(count));
      k--;
     }
     count++;
    }
    if(count > 0 && count < len)
     sb.append(message.substring(count));
    result = sb.toString();
   }
   else if(operation == 2) {
    StringBuilder sb = new StringBuilder();
    int count = 0;

    for(char ch : key.toCharArray()) {
     int len = message.length();
     int k = Character.getNumericValue(ch);
     if(count >= len)
      break;
     String str = Character.toString(message.charAt(count));
     if(k > 0) {
      sb.append(str);
     }
     while(k > 0) {
      message = message.replaceFirst(str, "");
      k--;
     }
    }
    sb.append(message);
    result = sb.toString();
   }

   if(result == null)
    return "-1";
   return result;
  } catch(Exception e) {
   return "-1";
  }
 }
}
Powered by Create your own unique website with customizable templates.