Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Check if a Subarray exists with sums as a multiple of k
Next article icon

Check if a subarray of length K with sum equal to factorial of a number exists or not

Last Updated : 12 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N integers and an integer K, the task is to find a subarray of length K with a sum of elements equal to factorial of any number. If no such subarray exists, print “-1”.

Examples:

Input: arr[] = {23, 45, 2, 4, 6, 9, 3, 32}, K = 5
Output: 2 4 6 9 3
Explanation:
Subarray {2, 4, 6, 9, 3} with sum 24 (= 4!) satisfies the required condition.

Input: arr[] = {23, 45, 2, 4, 6, 9, 3, 32}, K = 3
Output: -1
Explanation:
No such subarray of length K (= 3) exists.

Naive Approach: The simplest approach to solve the problem is to calculate the sum of all subarrays of length K and check if any of those sums is factorial of any number. If found to be true for any subarray, print that subarray. Otherwise, print "-1". 

Time Complexity: O(N*K)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use the Sliding Window technique to calculate the sum of all subarrays of length K and then check if the sum is a factorial or not. Below are the steps:

  1. Calculate the sum of first K array elements and store the sum in a variable, say sum.
  2. Then traverse the remaining array and keep updating sum to get the sum of the current subarray of size K by subtracting the first element from the previous subarray and adding the current array element.
  3. To check whether the sum is a factorial of a number or not, divide the sum by 2, 3, and so on until it cannot be divided further. If the number reduces to 1, the sum is the factorial of a number.
  4. If the sum in the above step is a factorial of a number, store the starting and ending index of that subarray to print the subarray.
  5. After completing the above steps, if no such subarray is found, print "-1". Otherwise, print the subarray whose start and end indices are stored.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to check if a number // is factorial of a number or not int isFactorial(int n) {     int i = 2;     while (n != 1) {          // If n is not a factorial         if (n % i != 0) {             return 0;         }         n /= i;         i++;     }     return i - 1; }  // Function to return the index of // the valid subarray pair<int, int> sumFactorial(     vector<int> arr, int K) {     int i, sum = 0, ans;      // Calculate the sum of     // first subarray of length K     for (i = 0; i < K; i++) {          sum += arr[i];     }      // Check if sum is a factorial     // of any number or not     ans = isFactorial(sum);      // If sum of first K length subarray     // is factorial of a number     if (ans != 0) {         return make_pair(ans, 0);     }      // Find the number formed from the     // subarray which is a factorial     for (int j = i; j < arr.size(); j++) {          // Update sum of current subarray         sum += arr[j] - arr[j - K];          // Check if sum is a factorial         // of any number or not         ans = isFactorial(sum);          // If ans is true, then return         // index of the current subarray         if (ans != 0) {             return make_pair(ans,                              j - K + 1);         }     }      // If the required subarray is     // not possible     return make_pair(-1, 0); }  // Function to print the subarray whose // sum is a factorial of any number void printRes(pair<int, int> answer,               vector<int> arr, int K) {      // If no such subarray exists     if (answer.first == -1) {          cout << -1 << endl;     }      // Otherwise     else {          int i = 0;         int j = answer.second;          // Iterate to print subarray         while (i < K) {              cout << arr[j] << " ";             i++;             j++;         }     } }  // Driver Code int main() {     vector<int> arr         = { 23, 45, 2, 4,             6, 9, 3, 32 };      // Given sum K     int K = 5;      // Function Call     pair<int, int> answer         = sumFactorial(arr, K);      // Print the result     printRes(answer, arr, K);      return 0; } 
Java
// Java program for the above approach  import java.util.*; import java.io.*;  class GFG{      // Pair class public static class Pair {     int x;     int y;          Pair(int x, int y)      {         this.x = x;         this.y = y;     } }  // Function to check if a number  // is factorial of a number or not  static int isFactorial(int n)  {      int i = 2;      while (n != 1)     {           // If n is not a factorial          if (n % i != 0)          {              return 0;          }          n /= i;          i++;      }      return i - 1;  }  // Function to return the index of  // the valid subarray  static ArrayList<Pair> sumFactorial(int arr[],                                     int K)  {      ArrayList<Pair> pair = new ArrayList<>();          int i, sum = 0, ans;       // Calculate the sum of      // first subarray of length K      for(i = 0; i < K; i++)     {          sum += arr[i];      }           // Check if sum is a factorial      // of any number or not      ans = isFactorial(sum);           // If sum of first K length subarray      // is factorial of a number      if (ans != 0)      {         Pair p = new Pair(ans, 0);         pair.add(p);         return pair;      }       // Find the number formed from the      // subarray which is a factorial      for(int j = i; j < arr.length; j++)     {           // Update sum of current subarray          sum += arr[j] - arr[j - K];           // Check if sum is a factorial          // of any number or not          ans = isFactorial(sum);           // If ans is true, then return          // index of the current subarray          if (ans != 0)         {              Pair p = new Pair(ans, j - K + 1);             pair.add(p);             return pair;         }      }       // If the required subarray is      // not possible      Pair p = new Pair(-1, 0);     pair.add(p);     return pair; }   // Function to print the subarray whose  // sum is a factorial of any number  static void printRes(ArrayList<Pair> answer,                       int arr[], int K)  {           // If no such subarray exists      if (answer.get(0).x == -1)      {                   // cout << -1 << endl;         System.out.println("-1");     }       // Otherwise      else      {          int i = 0;          int j = answer.get(0).y;           // Iterate to print subarray          while (i < K)          {              System.out.print(arr[j] + " ");             i++;              j++;          }      }  }   // Driver Code  public static void main(String args[])  {           // Given array arr[] and brr[]      int arr[] = { 23, 45, 2, 4,                    6, 9, 3, 32 };                         int K = 5;     ArrayList<Pair> answer = new ArrayList<>();          // Function call      answer = sumFactorial(arr,K);                          // Print the result      printRes(answer, arr, K); }  }  // This code is contributed by bikram2001jha 
Python3
# Python3 program for the above approach  # Function to check if a number # is factorial of a number or not def isFactorial(n):      i = 2          while (n != 1):                  # If n is not a factorial         if (n % i != 0):             return 0                  n = n // i         i += 1          return i - 1  # Function to return the index of # the valid subarray def sumFactorial(arr, K):      i, Sum = 0, 0      # Calculate the sum of     # first subarray of length K     while(i < K):         Sum += arr[i]         i += 1      # Check if sum is a factorial     # of any number or not     ans = isFactorial(Sum)      # If sum of first K length subarray     # is factorial of a number     if (ans != 0):         return (ans, 0)      # Find the number formed from the     # subarray which is a factorial     for j in range(i, len(arr)):              # Update sum of current subarray         Sum = Sum + arr[j] - arr[j - K]          # Check if sum is a factorial         # of any number or not         ans = isFactorial(Sum)          # If ans is true, then return         # index of the current subarray         if (ans != 0):             return (ans, j - K + 1)      # If the required subarray is     # not possible     return (-1, 0)  # Function to print the subarray whose # sum is a factorial of any number def printRes(answer, arr, K):      # If no such subarray exists     if (answer[0] == -1):         print(-1)      # Otherwise     else:         i = 0         j = answer[1]          # Iterate to print subarray         while (i < K):             print(arr[j], end = " ")             i += 1             j += 1  # Driver code  arr = [ 23, 45, 2, 4, 6, 9, 3, 32 ]  # Given sum K K = 5  # Function call answer = sumFactorial(arr, K)  # Print the result printRes(answer, arr, K)  # This code is contributed by divyeshrabadiya07 
C#
// C# program for  // the above approach  using System; using System.Collections.Generic; class GFG{      // Pair class public class Pair {   public int x;   public int y;    public Pair(int x, int y)    {     this.x = x;     this.y = y;   } }  // Function to check if a number  // is factorial of a number or not  static int isFactorial(int n)  {    int i = 2;    while (n != 1)   {      // If n is not      // a factorial      if (n % i != 0)      {        return 0;      }      n /= i;      i++;    }    return i - 1;  }  // Function to return the index of  // the valid subarray  static List<Pair> sumFactorial(int []arr,                                int K)  {    List<Pair> pair = new List<Pair>();   int i, sum = 0, ans;     // Calculate the sum of    // first subarray of length K    for(i = 0; i < K; i++)   {      sum += arr[i];    }     // Check if sum is a factorial    // of any number or not    ans = isFactorial(sum);     // If sum of first K length subarray    // is factorial of a number    if (ans != 0)    {     Pair p = new Pair(ans, 0);     pair.Add(p);     return pair;    }     // Find the number formed from the    // subarray which is a factorial    for(int j = i; j < arr.Length; j++)   {      // Update sum of current subarray      sum += arr[j] - arr[j - K];       // Check if sum is a factorial      // of any number or not      ans = isFactorial(sum);       // If ans is true, then return      // index of the current subarray      if (ans != 0)     {        Pair p = new Pair(ans, j - K + 1);       pair.Add(p);       return pair;     }    }     // If the required subarray is    // not possible    Pair p1 = new Pair(-1, 0);   pair.Add(p1);   return pair; }   // Function to print the subarray whose  // sum is a factorial of any number  static void printRes(List<Pair> answer,                       int []arr, int K)  {    // If no such subarray exists    if (answer[0].x == -1)    {      // cout << -1 << endl;     Console.WriteLine("-1");   }     // Otherwise    else    {      int i = 0;      int j = answer[0].y;       // Iterate to print subarray      while (i < K)      {        Console.Write(arr[j] + " ");       i++;        j++;      }    }  }   // Driver Code  public static void Main(String []args)  {        // Given array []arr and brr[]    int []arr = {23, 45, 2, 4,                 6, 9, 3, 32};    int K = 5;   List<Pair> answer = new List<Pair>();      // Function call    answer = sumFactorial(arr, K);    // Print the result    printRes(answer, arr, K); }  }  // This code is contributed by shikhasingrajput  
JavaScript
<script>      // JavaScript program for the above approach     // Function to check if a number     // is factorial of a number or not     function isFactorial(n)     {         let i = 2;         while (n != 1) {              // If n is not a factorial             if (n % i != 0) {                 return 0;             }             n = parseInt(n / i, 10);             i++;         }         return i - 1;     }      // Function to return the index of     // the valid subarray     function sumFactorial(arr,K)     {         let i, sum = 0, ans;          // Calculate the sum of         // first subarray of length K         for (i = 0; i < K; i++) {              sum += arr[i];         }          // Check if sum is a factorial         // of any number or not         ans = isFactorial(sum);          // If sum of first K length subarray         // is factorial of a number         if (ans != 0) {             return [ans, 0];         }          // Find the number formed from the         // subarray which is a factorial         for (let j = i; j < arr.length; j++) {              // Update sum of current subarray             sum += arr[j] - arr[j - K];              // Check if sum is a factorial             // of any number or not             ans = isFactorial(sum);              // If ans is true, then return             // index of the current subarray             if (ans != 0) {                 return [ans, j - K + 1];             }         }          // If the required subarray is         // not possible         return [-1, 0];     }      // Function to print the subarray whose     // sum is a factorial of any number     function printRes(answer,arr,K)     {          // If no such subarray exists         if (answer[0] == -1) {              document.write(-1);         }          // Otherwise         else {              let i = 0;             let j = answer[1];              // Iterate to print subarray             while (i < K) {                  document.write(arr[j] + " ");                 i++;                 j++;             }         }     }      // Driver Code      let arr= [ 23, 45, 2, 4,             6, 9, 3, 32 ];      // Given sum K     let K = 5;      // Function Call     let answer= sumFactorial(arr, K);      // Print the result     printRes(answer, arr, K);  </script> 

Output: 
2 4 6 9 3

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Check if a Subarray exists with sums as a multiple of k
author
shawavisek35
Improve
Article Tags :
  • Searching
  • Mathematical
  • DSA
  • Arrays
  • subarray
  • sliding-window
  • subarray-sum
Practice Tags :
  • Arrays
  • Mathematical
  • Searching
  • sliding-window

Similar Reads

  • Check for each subarray whether it consists of all natural numbers up to its length or not
    Given an array, arr[] representing a permutation of first N natural numbers in the range [1, N], the task for each ith index is to check if an i-length subarray exists or not such that it contains all the numbers in the range [1, i]. Note: 1 - based indexing used. Examples: Input: arr[] = {4, 5, 1,
    8 min read
  • Check if a Subarray exists with sums as a multiple of k
    Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer. Note: The length of the array won't exceed 10,000. You may assume th
    8 min read
  • Number of non-decreasing sub-arrays of length greater than or equal to K
    Given an array arr[] of N elements and an integer K, the task is to find the number of non-decreasing sub-arrays of length greater than or equal to K.Examples: Input: arr[] = {1, 2, 3}, K = 2 Output: 3 {1, 2}, {2, 3} and {1, 2, 3} are the valid subarrays.Input: arr[] = {3, 2, 1}, K = 1 Output: 3 Nai
    6 min read
  • Check if L sized Subarray of first N numbers can have sum S with one deletion allowed
    Consider an integer sequence A = {1, 2, 3, ...., N} i.e. the first N natural numbers in order and two integers, L and S. Check whether there exists a subarray of length L and sum S after removing at most one element from A. Examples: Input: N = 5, L = 3, S = 11Output: YESExplanation: We can remove 3
    6 min read
  • Number of subarrays with at-least K size and elements not greater than M
    Given an array of N elements, K is the minimum size of the sub-array, and M is the limit of every element in the sub-array, the task is to count the number of sub-arrays with a minimum size of K and all the elements are lesser than or equal to M. Examples: Input: arr[] = {-5, 0, -10}, K = 1, M = 15O
    7 min read
  • Maximum sum of K-length subarray with maximum count of distinct prime factors
    Given an array arr[] consisting of N positive integers and an integer K, the task is to find the maximum sum of array elements in a subarray having maximum sum of distinct prime factors in each K-length subarray. Note: If there are multiple answers then print the sum of the original subarray having
    11 min read
  • Check if a given number divides the sum of the factorials of its digits
    Given an integer N, the task is to check whether N divides the sum of the factorials of its digits. Examples: Input: N = 19 Output: Yes 1! + 9! = 1 + 362880 = 362881, which is divisible by 19. Input: N = 20 Output: No 0! + 2! = 1 + 4 = 5, which is not divisible by 20. Approach: First, store the fact
    9 min read
  • Check if a subarray of size K exists whose elements form a number divisible by 3
    Given an array arr[], of size N and a positive integer K, the task is to find a subarray of size K whose elements can be used to generate a number which is divisible by 3. If no such subarray exists, then print -1. Examples: Input: arr[] = {84, 23, 45, 12 56, 82}, K = 3 Output: 12, 56, 82 Explanatio
    8 min read
  • Check if it possible to partition in k subarrays with equal sum
    Given an array A of size N, and a number K. Task is to find out if it is possible to partition the array A into K contiguous subarrays such that the sum of elements within each of these subarrays is the same. Prerequisite: Count the number of ways to divide an array into three contiguous parts havin
    15+ min read
  • Make sum of all subarrays of length K equal by only inserting elements
    Given an array arr[] of length N such that (1 <= arr[i] <= N), the task is to modify the array, by only inserting elements within the range [1, N], such that the sum of all subarrays of length K become equal. Print the modified array, if possible. Else print "Not possible".Examples: Input: arr
    7 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