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
Sometimes, another interesting question comes-up during the face to face interviews -
1) How will you rotate the array for the given number of times.

Follow-up question can be -
2) Find a number in this rotated array.

Below is the code for both above queries -

import java.util.Arrays;

public class RotationSearch {

 public static void main(String[] args) {
  int[] array = sortedArray(5, 6);
  array = rotate(array, 0);
  System.out.println(exists(6, array));

 }

 /**
  * Finds the number in the provided array.
  * Instead of returning True/False, one can return the index also.
  * @param number
  * @param array
  * @return
  */
 private static boolean exists(int number, int[] array) {
  int len = array.length;
  // If len = 0 then it means whole array has been consumed to
  // search the number.
  if(len == 0)
   return false;
  int num = array[len/2];
  // If the number found then return True
  if(num == number)
   return true;
  // If the length of array is 1 & number is not present.
  else if(len == 1 && num != number)
   return false;
  // If the start of array is less than the middle number then
  // first half of array is sorted
  else if(array[0] <= num) {
   if(number >= array[0] && number < num) {
    array = Arrays.copyOfRange(array, 0, len/2);
    return exists(number, array);
   } else {
    array = Arrays.copyOfRange(array, len/2+1, len);
    return exists(number, array);
   }
  }
  // Otherwise the second half of the array is sorted.
  else {
   if(number >= num && number <= array[len-1]) {
    array = Arrays.copyOfRange(array, len/2+1, len);
    return exists(number, array);
   } else {
    array = Arrays.copyOfRange(array, 0, len/2);
    return exists(number, array);
   }
  }
 }

 
/**

  * Rotates the given array for provided number of times
  * @param array
  * @param times
  * @return
  */
 private static int[] rotate(int[] array, int times) {
  int len = array.length;
  int count = 0;
  int i = 0;
  Integer temp = null;
  times%=len;
  while(count < len) {
   int next = i+(times-1);
   if(next < len-1) {
    next++;
   } else {
    next = next - (len - 1);
   }
   if(temp == null) {
    temp = array[next];
    array[next] = array[i];
   } else {
    int cur = array[next];
    array[next] = temp;
    temp = cur;
   }
   i = next;
   count++;
  }
  return array;
 }

 
/**

  * Generates the sorted sequential array from start to end,
  * both inclusive.
  * @param start
  * @param end
  * @return
  */
 private static int[] sortedArray(int start, int end) {
  int len = end-start+1;
  int [] array = new int[len];
  int i = start;
  int k = 0;
  while(i <= end) {
   array[k] = i;
   i++;
   k++;
  }
  return array;
 }
}

Powered by Create your own unique website with customizable templates.