Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find final value if we double after every successful search in array
Next article icon

Find final value if we double after every successful search in array

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array and an integer k, traverse the array and if the element in array is k, double the value of k and continue traversal. In the end return value of k.

Examples: 

Input : arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2  Output: 16  Explanation:  First k = 2 is found, then we search for 4  which is also found, then we search for 8  which is also found, then we search for 16.     Input : arr[] = { 2, 4, 5, 6, 7 }, k = 3  Output: 3
Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

Method - 1: (Brute-force)

  1. Traverse each element of an array if arr[i] == k then k = 2 * k.  
  2. Repeat the same process for the max value of k.
  3. At last Return the value of k.

Implementation:

C++
// C++ program to find value if we double // the value after every successful search #include <bits/stdc++.h> using namespace std;  // Function to Find the value of k int findValue(int a[], int n, int k) {      bool exist = true;          // Search for k. After every successful     // search, double k and change exist to true     // and search again for k from the start of array          while(exist){                  exist = false;                  for (int i = 0; i < n; i++) {                          // Check is a[i] is equal to k             if (a[i] == k){                 k *= 2;                 exist = true;                 break;             }         }              }      return k; }  // Driver's Code int main() {     int arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2;     int n = sizeof(arr) / sizeof(arr[0]);          cout << findValue(arr, n, k);          return 0; } 
Java
// Java program to find value // if we double  the value after // every successful search class GFG {    // Function to Find the value of k   static int findValue(int arr[], int n, int k)   {      boolean exist = true;      // Search for k. After every successful     // search, double k and change exist to true     // and search again for k from the start of array      while(exist){        exist = false;        for (int i = 0; i < n; i++) {          // Check is a[i] is equal to k         if (arr[i] == k){           k *= 2;           exist = true;           break;         }       }      }      return k;   }    // Driver Code   public static void main(String[] args)   {     int arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2;     int n = arr.length;     System.out.print(findValue(arr, n, k));   } }  // This code is contributed by Aarti_Rathi 
C#
using System; /*   C# program to find value if we double   the value after every successful search */ public class GFG {     // Function to Find the value of k     static int findValue(int[] a, int n, int k)     {          bool exist = true;          // Search for k. After every successful         // search, double k and change exist to true         // and search again for k from the start of array          while (exist) {              exist = false;              for (int i = 0; i < n; i++) {                  // Check is a[i] is equal to k                 if (a[i] == k) {                     k *= 2;                     exist = true;                     break;                 }             }         }          return k;     }      // Driver Code     public static void Main()     {         int[] arr = { 2, 3, 4, 10, 8, 1 };         int k = 2;         int n = arr.Length;          Console.WriteLine(findValue(arr, n, k));     } } // This code is contributed by Aarti_Rathi 
Python3
#  Python program to find value if we double #  the value after every successful search  # Function to Find the value of k def findValue(a, n, k):      exist = True      while exist:         #  Search for k. After every successful         #  search, double k and change exist to true         # and search again for k from the start of array         exist = False          for i in range(n):             # Check is a[i] is equal to k             if a[i] == k:                 k *= 2                 exist = True                 break      return k   # Driver's Code arr = [2, 3, 4, 10, 8, 1] k = 2 n = len(arr) print(findValue(arr, n, k)) 
JavaScript
<script>    // JavaScript program to find value   // if we double  the value after   // every successful search    // Function to Find the value of k   function findValue(arr, n, k)   {      var exist = true;     // Search for k. After every successful     // search, double k and change exist to true     // and search again for k from the start of array     while(exist){                  exist = false;                  for(let i = 0; i < n; i++){             // Check is a[i] is equal to k             if(arr[i] == k) {                 k *= 2;                 exist = true;                 break;             }         }              }      return k;   }     // Driver code    let arr = [ 2, 3, 4, 10, 8, 1 ], k = 2;   let n = arr.length;   document.write(findValue(arr, n, k));  // This code is contributed by muditj148. </script> 

Output
16

Time Complexity : O(n^2) 

Auxiliary Space: O(1)

Method - 2: (Sort and the search)

  1. Sort the array
  2. Then you can just search for the element in one loop because we are sure that k*2 would be after k in this array. Therefore,  just multiply the value of k there in the loop only. 

Implementation:

C++
// CPP program to find value if we double // the value after every successful search #include <bits/stdc++.h> using namespace std;  // Function to Find the value of k int findValue(int a[], int n, int k) {      // Sort the array     sort(a, a + n);      // Search for k. After every successful     // search, double k.     for (int i = 0; i < n; i++) {                  // Check is a[i] is equal to k         if (a[i] == k)             k *= 2;     }      return k; }  // Driver's Code int main() {     int arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2;     int n = sizeof(arr) / sizeof(arr[0]);     cout << findValue(arr, n, k);     return 0; } 
Java
// Java program to find value // if we double  the value after // every successful search  class GFG {     // Function to Find the value of k     static int findValue(int arr[], int n, int k)     {          // Search for k. After every successful         // search, double k.         for (int i = 0; i < n; i++)             if (arr[i] == k)                 k *= 2;          return k;     }      // Driver Code     public static void main(String[] args)     {         int arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2;         int n = arr.length;         System.out.print(findValue(arr, n, k));     } } // This code is contributed by // Smitha Dinesh Semwal 
Python3
# Python program to find # value if we double # the value after every # successful search  # Function to Find the value of k   def findValue(arr, n, k):      # Search for k.     # After every successful     # search, double k.     for i in range(n):         if (arr[i] == k):             k = k * 2      return k  # Driver's Code   arr = [2, 3, 4, 10, 8, 1] k = 2 n = len(arr)  print(findValue(arr, n, k))  # This code is contributed # by Anant Agarwal. 
C#
// C# program to find value // if we double the value after // every successful search using System;  class GFG {      // Function to Find the value of k     static int findValue(int[] arr, int n, int k)     {          // Search for k. After every successful         // search, double k.         for (int i = 0; i < n; i++)             if (arr[i] == k)                 k *= 2;          return k;     }      // Driver Code     public static void Main()     {         int[] arr = { 2, 3, 4, 10, 8, 1 };         int k = 2;         int n = arr.Length;          Console.WriteLine(findValue(arr, n, k));     } }  // This code is contributed by vt_m. 
PHP
<?php // PHP program to find  // value if we double  // the value after every  // successful search  // Function to Find  // the value of k function findValue($arr, $n, $k)  {      // Search for k. After every      // successful search, double k.     for ($i = 0; $i < $n; $i++)          if ($arr[$i] == $k)         $k *= 2;          return $k; }  // Driver Code $arr = array(2, 3, 4, 10, 8, 1);  $k = 2; $n = count($arr); echo findValue($arr, $n, $k);  // This code is contributed by anuj_67. ?> 
JavaScript
<script>  // JavaScript program to find value // if we double  the value after // every successful search      // Function to Find the value of k     function findValue(arr, n, k)     {           // Search for k. After every successful         // search, double k.         for (let i = 0; i < n; i++)             if (arr[i] == k)                 k *= 2;           return k;     }     // Driver code          let arr = [ 2, 3, 4, 10, 8, 1 ], k = 2;         let n = arr.length;         document.write(findValue(arr, n, k));  </script> 

Output
16

Time Complexity : O(nlogn) 

Auxiliary Space: O(1)

Method - 3: (Hashing)

  1. Put all elements in hashmap.
  2. Search if k is in hashmap, If it is then multiply the value by k or return value of k.

Implementation:

C++
// CPP program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the value int findValue(int a[], int n, int k) {          // Unordered Map     unordered_set<int> m;        // Iterate from 0 to n - 1     for (int i = 0; i < n; i++)         m.insert(a[i]);      while (m.find(k) != m.end())         k = k * 2;      return k; }  // Driver's Code int main() {     int arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2;     int n = sizeof(arr) / sizeof(arr[0]);     cout << findValue(arr, n, k);     return 0; } 
Java
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; class GFG {   static int findValue(int[] a,int n,int k){      // Unordered set     HashSet<Integer> m = new HashSet<Integer>();      // Iterate from 0 to n - 1     for(int i=0;i<n;i++){       m.add(a[i]);     }      while (m.contains(k)){       k = k * 2;     }      return k;   }    // Drivers code   public static void main(String args[]){     int[] arr = { 2, 3, 4, 10, 8, 1 };     int k = 2;     int n = arr.length;     System.out.println(findValue(arr, n, k));   } }  // This code is contributed by shinjanpatra. 
Python3
# Python program for the above approach  # Function to find the value def findValue(a, n, k):          # Unordered Map     m = set()        # Iterate from 0 to n - 1     for i in range(n):         m.add(a[i])      while (k in m):         k = k * 2      return k  # Driver's Code  arr, k = [ 2, 3, 4, 10, 8, 1 ], 2 n = len(arr) print(findValue(arr, n, k))  # This code is contributed by shinjanpatra 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG {     static int findValue(int[] a, int n, int k)     {         // Unordered set         HashSet<int> m = new HashSet<int>();          // Iterate from 0 to n - 1         for (int i = 0; i < n; i++) {             m.Add(a[i]);         }         while (m.Contains(k)) {             k = k * 2;         }         return k;     }     // Drivers code     public static void Main(string[] args)     {         int[] arr = { 2, 3, 4, 10, 8, 1 };         int k = 2;         int n = arr.Length;         Console.WriteLine(findValue(arr, n, k));     } }  // This code is contributed by Tapesh(tapeshdua420) 
JavaScript
<script>  // JavaScript program for the above approach  // Function to find the value function findValue(a, n, k) {          // Unordered Map     let m = new Set();        // Iterate from 0 to n - 1     for (let i = 0; i < n; i++)         m.add(a[i]);      while (m.has(k))         k = k * 2;      return k; }  // Driver's Code  let arr = [ 2, 3, 4, 10, 8, 1 ], k = 2; let n = arr.length; document.write(findValue(arr, n, k));  // This code is contributed by shinjanpatra  </script> 

Output
16

Time Complexity: O(n)
Space Complexity: O(n)

Reference: "https://www.geeksforgeeks.org/flipkart-interview-experience-set-35-on-campus-for-sde-1/"


Next Article
Find final value if we double after every successful search in array

M

Mr.Gera
Improve
Article Tags :
  • Searching
  • DSA
  • Arrays
  • Flipkart
Practice Tags :
  • Flipkart
  • Arrays
  • Searching

Similar Reads

    Find if array has an element whose value is half of array sum
    Given a sorted array (with unique entries), we have to find whether there exists an element(say X) that is exactly half the sum of all the elements of the array including X. Examples: Input : A = {1, 2, 3} Output : YES Sum of all the elements is 6 = 3*2; Input : A = {2, 4} Output : NO Sum of all the
    10 min read
    Find a String in given Array of Strings using Binary Search
    Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1.Examples:Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index 2.
    6 min read
    Find elements of original array from doubled array
    Given an array arr[] of 2*N integers such that it consists of all elements along with the twice values of another array, say A[], the task is to find the array A[]. Examples: Input: arr[] = {4, 1, 18, 2, 9, 8}Output: 1 4 9Explanation:After taking double values of 1, 4, and 9 then adding them to the
    7 min read
    Find a Fixed Point (Value equal to index) in a given array | Duplicates Allowed
    Given an array of n integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the array can be negative.
    13 min read
    Count of elements that are binary searchable in the given array
    Given an array arr[] consisting of N integers, the task is to find the maximum count of integers that are binary searchable in the given array. Examples: Input: arr[] = {1, 3, 2}Output: 2Explanation: arr[0], arr[1] can be found. Input: arr[] = {3, 2, 1, 10, 23, 22, 21}Output: 3Explanation: arr[1], a
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences