• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Pro Programming

Professional way of Programming: Learn C, C++, Java, Python, Dot Net, Android the professional way

  • Home
  • C MCQs
  • C/C++ Programs
  • Java Programs
  • C#
  • Python
  • MySQL
  • Topics
    • Arrays
    • Strings
    • Link Lists
    • Trees
    • Shapes
  • Projects
  • Articles
  • Games
You are here: Home / Archives for Multiple Choice Quizzes

Multiple Choice Quizzes

Count pairs of non-overlapping palindromic sub-strings of the given string

Leave a Comment


#include <bits/stdc++.h>

using namespace std;

#define N 100

  

void pre_process(bool dp[N][N], string s)

{

  

    

    int n = s.size();

  

    

    

    for (int i = 0; i < n; i++) {

        for (int j = 0; j < n; j++)

            dp[i][j] = false;

    }

  

    

    for (int j = 1; j <= n; j++) {

  

        

        

        for (int i = 0; i <= n - j; i++) {

  

            

            if (j <= 2) {

  

                

                if (s[i] == s[i + j - 1])

                    dp[i][i + j - 1] = true;

            }

  

            

            else if (s[i] == s[i + j - 1])

                dp[i][i + j - 1] = dp[i + 1][i + j - 2];

        }

    }

}

  

int countPairs(string s)

{

  

    

    bool dp[N][N];

    pre_process(dp, s);

    int n = s.length();

  

    

    int left[n];

    memset(left, 0, sizeof left);

  

    

    int right[n];

    memset(right, 0, sizeof right);

  

    

    left[0] = 1;

  

    

    

    for (int i = 1; i < n; i++) {

  

        for (int j = 0; j <= i; j++) {

  

            if (dp[j][i] == 1)

                left[i]++;

        }

    }

  

    

    right[n - 1] = 1;

  

    

    

    for (int i = n - 2; i >= 0; i--) {

  

        right[i] = right[i + 1];

  

        for (int j = n - 1; j >= i; j--) {

  

            if (dp[i][j] == 1)

                right[i]++;

        }

    }

  

    int ans = 0;

  

    

    for (int i = 0; i < n - 1; i++)

        ans += left[i] * right[i + 1];

  

    return ans;

}

  

int main()

{

    string s = "abacaba";

    cout << countPairs(s);

  

    return 0;

}



Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Arrange first N natural numbers such that absolute difference between all adjacent elements > 1, Array, Backtracking, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Campus Ambassador Program, Campus Geek of the Month, Careers, Check if a word exists in a grid or not, Combinatorial, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Contact Us, Contests, contribute.geeksforgeeks.org, Core Subjects ►, Count All Palindromic Subsequence in a given String, Count all Prime Length Palindromic Substrings, Count number of equal pairs in a string, count number of substrings that start and end with 1., Count Numbers with N digits which consists of odd number of 0's, Count of distinct substrings of a string using Suffix Array, Count of distinct substrings of a string using Suffix Trie, Count of Numbers in a Range divisible by m and having digit d in even positions, Count of Numbers in a Range where digit d occurs exactly K times, Count of Numbers in Range where first digit is equal to last digit of the number, Count of Numbers in Range where the number does not contain more than K non zero digits, Count of Palindromic substrings in an Index range, Count of sub-sets of size n with total element sum divisible by 3, Count of substrings of a binary string containing K ones, Count palindromic characteristics of a String, Count paths with distance equal to Manhattan distance, Count the number of special permutations, Count the number of vowels occurring in all the substrings of given string, Count unordered pairs (i, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Deletions of "01" or "10" in binary string to make it free from "01" or "10", Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Experienced Interviews, Find a palindromic string B such that given String A is a subsequense of B, Find the count of palindromic sub-string of a string in its sorted form, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating Lyndon words of length n, Geometric Algorithms, Given a binary string, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, HTML, HTML & XML, ide.geeksforgeeks.org, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, j) such that product of a[i] and a[j] is power of two, Java, Java Program to print distinct permutations of a string, JavaScript, jQuery, K length words that can be formed from given characters without repetition, Languages, Languages ►, Languages ▼, Last Minute Notes, LinkedList, Longest subsequence such that adjacent elements have at least one common digit, Machine Learning, Make Binary Search Tree, Make palindromic string non-palindromic by rearranging its letters, Mathematical Algorithms, Matrix, Maximum sum from three arrays such that picking elements consecutively from same is not allowed, Microprocessor, Minimum cuts required to convert a palindromic string to a different palindromic string, Multiple Choice Quizzes, Number of moves required to guess a permutation., Number of permutations of a string in which all the occurrences of a given character occurs together, Number of submatrices with all 1s, Number of submatrices with OR value 1, Number of trailing zeroes in base 16 representation of N!, Number of triangles that can be formed with given N points, Number of unique pairs in an array, Number of ways of scoring R runs in B balls with at most W wickets, Number of ways to go from one point to another in a grid, Number of ways to select a node from each connected component, Operating Systems, palindrome, Pattern Searching, Permutations of string such that no two vowels are adjacent, PHP, Placement Course, Practice, Practice Company Questions, Privacy Policy, Program Output, Program to calculate the value of nCr Efficiently, Program to calculate the value of nPr, Project, Puzzles, Python, Queries to check if substring[L…R] is palindrome or not, Queue, Quizzes ▼, Randomized Algorithms, Rearrange the string to maximize the number of palindromic substrings, Recommended: Please try your approach on, School Programming, Searching Algorithms, Skip to content, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, substring, Suggest an Article, Sum of (maximum element - minimum element) for all the subsets of an array., Sum of all Submatrices of a Given Matrix, Sum of bitwise AND of all submatrices, Sum of Bitwise-OR of all Submatrices, Sum of XOR of all subarrays, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Total number of subsets in which the product of the elements is even, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Understanding The Coin Change Problem With Dynamic Programming, Video Tutorials, Videos, Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1, Ways to paint N paintings such that adjacent paintings don't have same colors, Web Technology, What’s Difference?, Write an Article, Write Interview Experience

Hike Interview Experience | Set 7(For SDE iOS) | 2+ Years Experience

Leave a Comment


I have recently attend Hike Hiring Drive for iOS Developer in Delhi office. Candidates are  0-2, 2-4 and 4+ years of experience . I have got referral from recruiter on LinkedIn .

Round 1: Mobile App –  (1:30 hour ) They have provided Flickr Api, task is build iOS App that fetch images using search bar input and display the images . Make sure UI should not blocked, mulitple request handling while user typing, code structure, pagination and readability and image caching is plus if you have implemented .

I have build the app in 50 minutes – Link to see   https://github.com/Vasu05/Hike-Messenger-Hiring-iOS-Test

After the completion of app, My App is reveiwed by iOS manager .He was cool and friendly  .He asked model structure I’ve followed, there is crash in my app, asked me debug and I did , told him the crash reason .  He asked about GCD , asked for code optimization .He asked how to detect if user scrolled bottom of page . He inspect the app thoroughly, he was typing, cancelling, clearing data to see behaivour of app. He was impressed since I’ve build all the major features with code optimization .  Then we have discussion on current projects I’m into, what I have built in past .This reveiw round was around for 1:20 hr . He asked me to have a lunch and wait for second round .

Round 2: DS Algo (30 min) –


  • Find two elements with sum equal to value x in Array.I did it using hashmap .
  • Is Tree is BST or Not.
  • LRU Implementation
  • Discussion on threads handling in iOS

Proper code was required, they have given enough time to think and asked for better approach . I code all three on board with explanation . Interviewer was impressed, asked me wait for another round .

Round 3: This round was supposed to taken by  Vice President of company  but he was busy with another candidates so another lead come and asked me for another round . He asked two questions

  • Detect loop in linkedlist and remove the loop.
  • get merging point of two  linkedlist.

Meanwhile I was writing code for second questions on paper, he said  he was done with interview and asked me to meet VP for further round .

Round 4 : This round taken by VP of company . He gaves introduction, what he did, what they are focusing on and talk about how they are different from another messaging apps in market . He asked me whether you prefer pen and paper or writing on screen, then he asked me come to board, it was samsung TV  where i supposed to write code with pen . He asked –

  • Infinite stream of words  you have to tell k most occuring words . I told him approach with heap and trie, he asked me use another data structure for searching, i gave him ternary tree apporoach still he was expecting better and gave me hint to use map then gave solution using heap and hashmap . He asked me to code .
  • check wether binary tree is min heap or not  . He left the room and asked me think optimise solution . He comes after 30 minutes break in between i’ve written properties of binary tree and heap then write code for checking tree is min heap or not .He was satisfied .
  • He gave me design question – he asked me build sticker search option while user is typing  . I told him about memory caching he asked me what all typing of caching we can used . I told him there is App cache maintain by app, disk memory and network memory . I have made  diagram how search query will work step by step . Then we have discussion on multiple characters handling when user typing, I said we can use timer to process new request . Then he asked me main thread should not be blocked while user interacting with screen . I told him to use GCD’s and we have long discussion on this . He was satisfied, it was long round, he was helping me when I’m stuck . Then we discussed about company culture, whether he still code, how he started with Hike messenger . He asked me to wait for another round .
  • There are many another questions which I’m not remember .

This round goes for 1:40 hour .

After All this i was very exhaused since I have given all question correctly this continous evaluation was starts from 10:30 in morning .

It was around 5:30 when they scheduled another round of interview .

Round 5: Interviewer scanned my resume, aksed me for brief introduction.I explained him my current company projects and college projects. He was senior backened developer . He starts asking me Java questions . I told him I was not able in touch with since 1.5 years still he asked.

  • write code for 1 writer and n reader problem . I told him we can use locks (mutes and semaphore) and gave him solution .
  • He asked virtual pointers – I told him I don’t remember .
  • Stack vs Heap Memory . I gave him explanation with example .
  • Singleton class, why we are using this . He was not satisfied with explaination .
  • He asked basic java questions like what public, private, why there is single main function in Java .

After all this recruiter asked me to leave and next day they said last round was not as per expectation . I’m not selected. Tips –  prepare your interview like college placement, they can aks anything even if  its not related to your hiring post .

Join Free Interview Preparation Course


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Microsoft Interview Questions (3.5 years)

Next

last_page Software Engineer Interview at GE Digital | Hyderabad (off-campus)







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Adobe Interview Experience (5 Rounds), Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Amazon internship interview experience (on campus), Amazon Interview Experience (On campus 2018), Amazon Interview Experience (On-Campus for SDE-1) 2019, Amazon Interview Experience (On-Campus), Amazon Interview Experience (Pool campus-2019), Amazon Interview Experience | SDE-1 offcampus, Amazon interview experience for Experienced, Amazon interview experience for SDE II, Amazon Interview Experience SDE (On Campus 2019), Amazon Interview Experience SDE 1, Amazon Interview Experience SDE 1 (2.5 Years Experienced), Amazon Interview Experience SDE 2, Amazon Interview Experience SDE ll, Amazon Interview Experience SDE Off Campus, Amazon Interview Experience SDE1, Amazon SDE-2 Experience (6.5 Years Exp), Analysis of Algorithms, Aptitude, Arcesium Interview Experience | Set 5 (3+ years experience - Developer profile), Array, Backtracking, Bharti SoftBank (Hike) Interview Experience | Set 1, Bharti SoftBank (Hike) Interview Experience | Set 2, Bharti SoftBank (Hike) Interview Experience | Set 3 (For SDE 1), Bharti SoftBank (Hike) Interview Experience | Set 4 (Off-Campus for SDE1), Bharti SoftBank (Hike) Interview Experience | Set 5 (Off-Campus for Portal Team), Bharti SoftBank (Hike) Interview Experience | Set 6, Bharti SoftBank (Hike) Interview Experience | Set 7 (For SDE), Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, Brocade Interview Experience | Set 2 (For Software Engineer 0-2.5 Years Experience), C, Campus Ambassador Program, Campus Geek of the Month, Careers, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Contact Us, Contests, contribute.geeksforgeeks.org, Core Subjects ►, Courses, Coviam Software Developer Internship Experience, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Experienced Interviews, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Geometric Algorithms, Goldaman Sachs Interview Experience (1+ year experienced), Goldman Sachs Interview (for Experienced), Goldman Sachs Interview Experience, Goldman Sachs Interview Experience | Set 23 (2+ years Experience for Java Developer Role), Goldman Sachs Interview Experience 2018, Goldman Sachs Interview Experience 2019, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, Hike, Hike Interview Experience, Hike Interview Experience | QA Profile, Hike Interview Experience | Set 5, Hike Interview Experience | Set 6 (For SDE), HTML, HTML & XML, https://github.com/Vasu05/Hike-Messenger-Hiring-iOS-Test, Hyderabad, ide.geeksforgeeks.org, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Java, JavaScript, Join Free Interview Preparation Course, JP Morgan Chase & Co. (JPMC) Interview Experience | (Full time Software Engineer), jQuery, Languages, Languages ►, Languages ▼, Last Minute Notes, LinkedList, Machine Learning, MakeMyTrip Interview Experience 2019, Mathematical Algorithms, Matrix, Microprocessor, Microsoft IDC Internship On-Campus Interview Experience 2018, Microsoft IDC Interview Experience, Microsoft Internship Interview Experience, Microsoft Interview Experience (Full Time 2018 Washington DC - with 2.5 years of experience), Microsoft Interview Experience | SDE - 2018, Microsoft Interview Experience 2018 @ IIT, Microsoft Interview Experience for Azure Team Hyderabad, Microsoft Interview Interview Experience for Full Time, Microsoft Interview Questions (3.5 years), Multiple Choice Quizzes, Off-Campus Placement Preparation, Operating Systems, Pattern Searching, PHP, Placement Course, Practice, Practice Company Questions, Privacy Policy, Program Output, Project, Puzzles, Python, Qualcomm Interview Experience (Off-Campus), Queue, Quizzes ▼, Randomized Algorithms, Samsung Interview Experience | (On-Campus for R & D Noida), Samsung R & D Campus drive 2018, Samsung R & D Interview questions, School Programming, Searching Algorithms, Skip to content, Software Engineer Interview at GE Digital | Hyderabad (off-campus), Software Engineer Interview at Google, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, Suggest an Article, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Wipro Elite Interview Experience (On Campus), Write an Article, Write Interview Experience, Write your Interview Experience

Maximum volume of cube for every person when edge of N cubes are given

Leave a Comment


Given an array of N integers which denotes the edges of N cubical structures respectively. Also given are M integers which denotes the number of peoples. The task is to find the maximum amount of volume of a cube that can be given to every person.

Note: Cubes can be cut of any shape from any of the N cubes.

Examples:

Input: a[] = {1, 1, 1, 2, 2}, m = 3
Output: 4
All three person get a slice of volume 4 each
Person 1 gets a slice of volume 4 from the last cube.
Person 2 gets a slice of volume 4 from the last cube.
Person 3 gets a slice of volume 4 from the second last cube.

Input: a[] = {2, 2, 2, 2, 2}, m = 4
Output: 8


Naive Approach: A naive approach is to first calculate the volume of all of the cubes and then linearly check for every volume that it can be distributed among all M people or not and find the maximum volume among all such volumes.

Time Complexity: O(N2)

Efficient Approach: An efficient approach is to use binary search to find the answer. Since the edge lengths are given in the array, convert them to the volume of the respective cubes.

Find the maximum volume among volumes of all of the cubes. Say, the maximum volume is maxVolume. Now, perform binary search on the range [0, maxVolume].

  • Calculate the middle value of the range, say mid.
  • Now, calculate the total number of cubes that can be cut of all of the cubes of volume mid.
  • If the total cubes that can be cut exceed the number of persons, then that amount of volume of cubes can be cut for every person, hence we check for a larger value in the range [mid+1, maxVolume].
  • If the total cubes do not exceed the number of persons, then we check for an answer in the range [low, mid-1].

Below is the implementation of the above approach:

  

#include <bits/stdc++.h>

using namespace std;

  

int getMaximumVloume(int a[], int n, int m)

{

    int maxVolume = 0;

  

    

    

    for (int i = 0; i < n; i++) {

        a[i] = a[i] * a[i] * a[i];

  

        maxVolume = max(a[i], maxVolume);

    }

  

    

    

    int low = 0, high = maxVolume;

  

    

    int maxVol = 0;

  

    

    while (low <= high) {

  

        

        int mid = (low + high) >> 1;

  

        

        int cnt = 0;

        for (int i = 0; i < n; i++) {

            cnt += a[i] / mid;

        }

  

        

        

        

        if (cnt >= m) {

  

            

            low = mid + 1;

  

            

            

            maxVol = max(maxVol, mid);

        }

  

        

        else

            high = mid - 1;

    }

  

    return maxVol;

}

  

int main()

{

    int a[] = { 1, 1, 1, 2, 2 };

    int n = sizeof(a) / sizeof(a[0]);

    int m = 3;

  

    cout << getMaximumVloume(a, n, m);

  

    return 0;

}

Time Complexity: O(N * log (maxVolume))



Striver(underscore)79 at Codechef and codeforces D


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Partition the array into three equal sum segments







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Array, Array Manipulation and Sum, Arrays, Backtracking, Binary Search, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Calculate the total fine to be collected, Campus Ambassador Program, Campus Geek of the Month, Careers, Check if an array is sorted and rotated, Check if X can give change to every person in the Queue, Check whether an Array is Subarray of another Array, Coin game of two corners (Greedy Approach), Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Constructive Algorithms, Contact Us, Contests, contribute.geeksforgeeks.org, Convert a String to Integer Array in C/C++, Core Subjects ►, Count array elements that divide the sum of all other elements, Count distinct elements in an array, Count of pairs (x, Courses, Coviam Software Developer Internship Experience, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Design a Hit Counter, Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Experienced Interviews, Find triplets in an array whose AND is maximum, Find two numbers whose divisors are given in a random order, For each element in 1st array count elements less than or equal to it in 2nd array | Set 2, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating subarrays using recursion, Geometric Algorithms, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, How do Dynamic arrays work?, HTML, HTML & XML, ide.geeksforgeeks.org, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Java, JavaScript, jQuery, K maximum sum combinations from two arrays, Languages, Languages ►, Languages ▼, Largest number in an array that is not a perfect cube, Largest palindromic number in an array, Largest perfect cube number in an Array, Last Minute Notes, Length of the longest alternating subarray, Length of the longest Subarray with only Even Elements, LinkedList, Longest subarray having maximum sum, Longest subsequence such that adjacent elements have at least one common digit, Machine Learning, Make all numbers of an array equal, MakeMyTrip Interview Experience 2019, Mathematical Algorithms, Matrix, Maximum even sum subsequence, Maximum length of rod for Q-th person, Maximum Sum Path in Two Arrays, Maximum sum rectangle in a 2D matrix | DP-27, Maximum triplet sum in array, Maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]| when elements are from 1 to n, Maximum value of |arr[i] - arr[j]| + |i - j|, Maximum value of arr[i] % arr[j] for a given array, Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ), Microprocessor, Minimum elements to be removed such that sum of adjacent elements is always even, Minimum number of items to be delivered, Minimum number of swaps required to sort an array | Set 2, Minimum operations required to make all the array elements equal, Multidimensional Arrays in Java, Multiple Choice Quizzes, Next greater element in same order as input, Operating Systems, Partition the array into three equal sum segments, Pattern Searching, PHP, Placement Course, Practice, Practice Company Questions, Privacy Policy, Program for K Most Recently Used (MRU) Apps, Program Output, Program to check if an array is palindrome or not using Recursion, Program to find the Hidden Number, Project, Puzzles, Python, Queue, Quizzes ▼, Randomized Algorithms, Reach the numbers by making jumps of two given lengths, Rearrange Odd and Even values in Alternate Fashion in Ascending Order, Remove duplicates from unsorted array, School Programming, Searching Algorithms, Skip to content, Sliding Window Maximum (Maximum of all subarrays of size k), Smallest perfect Cube divisible by all elements of an array, Software Engineering, Some rights reserved, Sort elements by frequency | Set 5 (using Java Map), Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, Subsequence with maximum odd sum, Suggest an Article, Sum of all odd frequency elements in an array, Sum of minimum elements of all subarrays, Sum of XOR of all subarrays, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write an Article, Write Interview Experience, y) in an array such that x < y

Program to calculate the value of nPr

Leave a Comment


Given two numbers n and r, the task is to find the value of nPr.

nPr represents n permutation r which is calculated as n!/(n-k)!. Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n!, where “!” represents factorial.

nPr = n! / (n - r)!

Program:

  

import java.util.*;

  

public class GFG {

  

    static int fact(int n)

    {

        if (n <= 1)

            return 1;

        return n * fact(n - 1);

    }

  

    static int nPr(int n, int r)

    {

        return fact(n) / fact(n - r);

    }

  

    public static void main(String args[])

    {

        int n = 5;

        int r = 2;

  

        System.out.println(n + "P" + r + " = "

                           + nPr(n, r));

    }

}


Optimization for multiple queries of nPr

If there are multiple queries for nPr, we may precompute factorial values and use same for every call. This would avoid computation of same factorial values again and again.




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Check if the given array is mirror-inverse










Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Arrange first N natural numbers such that absolute difference between all adjacent elements > 1, Array, Backtracking, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, C Program for factorial of a number, C program to calculate the value of nPr, Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles, Campus Ambassador Program, Campus Geek of the Month, Careers, Check if the given array is mirror-inverse, Combinatorial, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Count number of triplets with product equal to given number with duplicates allowed, Count Numbers with N digits which consists of odd number of 0's, Count of Numbers in a Range divisible by m and having digit d in even positions, Count of Numbers in a Range where digit d occurs exactly K times, Count of Numbers in Range where first digit is equal to last digit of the number, Count of Numbers in Range where the number does not contain more than K non zero digits, Count of sub-sets of size n with total element sum divisible by 3, Count ordered pairs of positive numbers such that their sum is S and XOR is K, Count paths with distance equal to Manhattan distance, Count the number of special permutations, Count unordered pairs (i, Count ways to distribute m items among n people, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Deletions of "01" or "10" in binary string to make it free from "01" or "10", Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Experienced Interviews, Factorial, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating Lyndon words of length n, Geometric Algorithms, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Hashing in Java, Heap, HTML, HTML & XML, ide.geeksforgeeks.org, Implementing a Linked List in Java using Class, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, j) such that product of a[i] and a[j] is power of two, Java, Java Program for Cutting a Rod | DP-13, Java Program for Program for array rotation, Java Program for Program to calculate area of a Tetrahedron, Java Program for Program to find area of a circle, Java Program for QuickSort, Java Program to print distinct permutations of a string, Java Program to take Screenshots, Java Programs, JavaScript, jQuery, K length words that can be formed from given characters without repetition, Languages, Languages ►, Languages ▼, Last Minute Notes, LinkedList, Machine Learning, Mathematical Algorithms, Matrix, Microprocessor, Min Heap in Java, Minimum and Maximum number of pairs in m teams of n people, Multiple Choice Quizzes, Number of moves required to guess a permutation., Number of permutations of a string in which all the occurrences of a given character occurs together, Number of Simple Graph with N Vertices and M Edges, Number of submatrices with OR value 1, Number of trailing zeroes in base 16 representation of N!, Number of triangles that can be formed with given N points, Number of unique pairs in an array, Operating Systems, Pattern Searching, permutation, Permutations of string such that no two vowels are adjacent, PHP, Placement Course, Practice, Practice Company Questions, Privacy Policy, Program for factorial of a number, Program Output, Program to Add Two Complex Numbers, Program to calculate the value of nCr Efficiently, Program to calculate value of nCr, Program to find the sum of the series (1/a + 2/a^2 + 3/a^3 + ... + n/a^n), Program to validate a user using JSP, Project, Puzzles, Python, Queue, Quick Sort vs Merge Sort, Quizzes ▼, Randomized Algorithms, Recommended: Please try your approach on, Samsung Semiconductor Institute of Research(SSIR Software) Intern/FTE | Set-2, School Programming, Searching Algorithms, Skip to content, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, Suggest an Article, Sum of all Submatrices of a Given Matrix, Sum of bitwise AND of all submatrices, Sum of Bitwise-OR of all Submatrices, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Total number of subsets in which the product of the elements is even, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Understanding The Coin Change Problem With Dynamic Programming, Video Tutorials, Videos, Walmart Labs Interview Experience ( On Campus FT + 6 month Internship ), Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1, Ways to paint N paintings such that adjacent paintings don't have same colors, Web Technology, What’s Difference?, Write an Article, Write Interview Experience

Python | Bigram formation from given list

Leave a Comment


When we are dealing with text classification, sometimes we need to do certain kind of natural language processing and hence sometimes require to form bigrams of words for processing. In case of absence of appropriate library, its difficult and having to do the same is always quite useful. Let’s discuss certain ways in which this can be achieved.

Method #1 : Using list comprehension + enumerate() + split()
The combination of above three functions can be used to achieve this particular task. The enumerate function performs the possible iteration, split function is used to make pairs and list comprehension is used to combine the logic.

   

test_list = ['geeksforgeeks is best', 'I love it']

  

print ("The original list is : " + str(test_list))

  

res = [(x, i.split()[j + 1]) for i in test_list 

       for j, x in enumerate(i.split()) if j < len(i.split()) - 1]

  

print ("The formed bigrams are : " + str(res))

Output :

The original list is : [‘geeksforgeeks is best’, ‘I love it’]
The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]

 
Method #2 : Using zip() + split() + list comprehension
The task that enumerate performed in the above method can also be performed by the zip function by using the iterator and hence in a faster way. Let’s discuss certain ways in which this can be done.

   

test_list = ['geeksforgeeks is best', 'I love it']

  

print ("The original list is : " + str(test_list))

  

res = [i for j in test_list 

       for i in zip(j.split(" ")[:-1], j.split(" ")[1:])]

  

print ("The formed bigrams are : " + str(res))

Output :

The original list is : [‘geeksforgeeks is best’, ‘I love it’]
The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Python | Unique values in Matrix







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Amazon product price tracker using Python, Analysis of Algorithms, Aptitude, Array, Backtracking, Best Python libraries for Machine Learning, Binary Search (bisect) in Python, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Campus Ambassador Program, Careers, Check for balanced parentheses in Python, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Constructors in Python, Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Dealing with Rows and Columns in Pandas DataFrame, Decorators in Python, Decorators with parameters in Python, Design Patterns, Difference between C and Python, Digital Electronics, Divide and Conquer, Dividing a Large file into Separate Modules in C/C++, DS ▼, Engg. Mathematics, Experienced Interviews, Face Detection using Python and OpenCV with webcam, Find K Closest Points to the Origin, Functions in Python, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating subarrays using recursion, Geometric Algorithms, Gradient Descent in Linear Regression, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, How to assign values to variables in Python and other languages, HTML, HTML & XML, ide.geeksforgeeks.org, Indentation and Comment in Python, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Iterative Letter Combinations of a Phone Number, Java, Java and Python, JavaScript, jQuery, Languages, Languages ►, Languages ▼, Last Minute Notes, Linear Regression Using Tensorflow, LinkedList, Machine Learning, Mathematical Algorithms, Matrix, Memoization using decorators in Python, Microprocessor, ML | Cancer cell classification using Scikit-learn, ML | Linear Regression, ML | Unsupervised Face Clustering Pipeline, Multiple Choice Quizzes, Namespaces and Scope in Python, Natural-language-processing, Operating Systems, Operator Overloading in Python, Output of Python Programs | (Dictionary), Pattern Searching, PHP, Placement Course, Polymorphism in Python, Practice, Practice Company Questions, Privacy Policy, Program Output, Project, Puzzles, Python, Python | Catching the ball game, Python | Convert a nested list into a flat list, Python | Convert a string representation of list into list, Python | Convert list of string into sorted list of integer, Python | Convert list of string to list of list, Python | Convert list of tuples into list, Python | Count occurrences of a character in string, Python | Find maximum length sub-list in a nested list, Python | Generate QR Code using pyqrcode module, Python | Image Classification using keras, Python | Implementation of Movie Recommender System, Python | Implementation of Polynomial Regression, Python | Insert list in another list, Python | Maximum sum of elements of list in a list of lists, Python | NLP analysis of Restaurant reviews, Python | Output Formatting, Python | Output using print() function, Python | Pandas Split strings into two List/Columns using str.split(), Python | Program to generate one-time password (OTP), Python | range() method, Python | Remove all values from a list present in other list, Python | Sort list according to other list order, Python | Sort list of list by specified index, Python | Sort the values of first list using second list, Python | Unique values in Matrix, Python | Ways to check if element exists in list, Python | Ways to sum list of lists and return sum list, Python for Data Science, Python in Competitive Programming, Python List Comprehension | Segregate 0's and 1's in an array list, Python list sort(), Python list-programs, Python program to add two numbers, Python program to check whether a number is Prime or not, Python program to create a list of tuples from given list having number and its cube in each tuple, Python program to find day of the week for a given date, Python program to print all Prime numbers in an Interval, Python program to swap two elements in a list, Python Programs, Queue, Quizzes ▼, Randomized Algorithms, School Programming, Searching Algorithms, Skip to content, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Statement, Strings, Structuring Python Programs, Students ▼, Subjective Questions, Suggest an Article, Taking input from console in Python, Taking input in Python, Taking multiple inputs from user in Python, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write an Article, Write Interview Experience

Python | Convert case of elements in a list of strings

Leave a Comment


Given a list of strings, write a Python program to convert all string from lowercase/uppercase to uppercase/lowercase.

Input : ['GeEk', 'FOR', 'gEEKS']
Output: ['geeks', 'for', 'geeks']

Input : ['fun', 'Foo', 'BaR']
Output: ['FUN', 'FOO', 'BAR']

 
Method #1 : Convert Uppercase to Lowercase using map function

  

out = map(lambda x:x.lower(), ['GeEk', 'FOR', 'gEEKS'])

  

output = list(out)

  

print(output)

Output:


['geek', 'for', 'geeks']

 
Method #2: Convert Lowercase to Uppercase using List comprehension

  

input = ['fun', 'Foo', 'BaR']

  

lst = [x.upper() for x in input]

  

print(lst)

Output:


['FUN', 'FOO', 'BAR']




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Python | Sum values for each key in nested dictionary










Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Amazon product price tracker using Python, Analysis of Algorithms, Aptitude, Array, Backtracking, Best Python libraries for Machine Learning, Binary Search (bisect) in Python, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Campus Ambassador Program, Careers, Check for balanced parentheses in Python, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Constructors in Python, Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Counting the frequencies in a list using dictionary in Python, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Dealing with Rows and Columns in Pandas DataFrame, Decorators in Python, Decorators with parameters in Python, Design Patterns, Digital Electronics, Divide and Conquer, Dividing a Large file into Separate Modules in C/C++, DS ▼, Engg. Mathematics, Experienced Interviews, Face Detection using Python and OpenCV with webcam, Functions in Python, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating subarrays using recursion, Geometric Algorithms, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, How to assign values to variables in Python and other languages, HTML, HTML & XML, ide.geeksforgeeks.org, Indentation and Comment in Python, Inheritance in Python, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Java, Java and Python, JavaScript, Languages, Languages ►, Languages ▼, Last Minute Notes, Linear Regression Using Tensorflow, LinkedList, Machine Learning, Mathematical Algorithms, Matrix, Memoization using decorators in Python, Microprocessor, ML | Cancer cell classification using Scikit-learn, ML | Linear Regression, Multiple Choice Quizzes, Namespaces and Scope in Python, Operating Systems, Operator Overloading in Python, Output of Python Programs | (Dictionary), Pattern Searching, PHP, Placement Course, Polymorphism in Python, Practice, Practice Company Questions, Priority Queue in Python, Privacy Policy, Program Output, Project, Puzzles, Python, Python | Catching the ball game, Python | Convert a list into a tuple, Python | Convert a list of characters into a string, Python | Convert a list of multiple integers into a single integer, Python | Convert a list of Tuples into Dictionary, Python | Convert a nested list into a flat list, Python | Convert an array to an ordinary list with the same items, Python | Convert list of string to list of list, Python | Convert list of strings and characters to list of characters, Python | Convert number to list of integers, Python | Convert set into a list, Python | Count occurrences of a character in string, Python | Delete rows/columns from DataFrame using Pandas.drop(), Python | Frequency of each character in String, Python | Generate QR Code using pyqrcode module, Python | Image Classification using keras, Python | Implementation of Movie Recommender System, Python | Implementation of Polynomial Regression, Python | Maximum sum of elements of list in a list of lists, Python | NLP analysis of Restaurant reviews, Python | Output Formatting, Python | Output using print() function, Python | Pandas Split strings into two List/Columns using str.split(), Python | Program to convert String to a List, Python | Program to generate one-time password (OTP), Python | range() method, Python | Remove empty strings from list of strings, Python | Sum values for each key in nested dictionary, Python for Data Science, Python in Competitive Programming, Python List, Python list sort(), Python list-programs, Python program to add two numbers, Python program to check whether a number is Prime or not, Python program to convert a list to string, Python program to find day of the week for a given date, Python program to print all Prime numbers in an Interval, Python program to swap two elements in a list, Python Programs, Python regex to find sequences of one upper case letter followed by lower case letters, Python String, Queue, Quizzes ▼, Randomized Algorithms, School Programming, Searching Algorithms, Skip to content, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Statement, Strings, Structuring Python Programs, Students ▼, Subjective Questions, Suggest an Article, Taking input from console in Python, Taking input in Python, Taking multiple inputs from user in Python, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write an Article, Write Interview Experience

  • Page 1
  • Page 2
  • Page 3
  • Next Page »

Primary Sidebar

Recent Posts

  • Engineering Chemistry Questions and Answers – Application of Colloids
  • MongoDB Beginners Tutorial
  • 10 Projects That Every Developer Should Lay Their Hands-On
  • Engineering Chemistry Questions and Answers – Detergents
  • What is Blockchain? How the Blockchain Network Actually Works?
  • Privacy Policy
  • About
  • Contact US

© 2019 ProProgramming
 Privacy Policy About Contact Us