The document discusses solving programming challenges on Coursera. It introduces two simple challenges: computing the sum of two digits and finding the maximum pairwise product in an array. For each challenge, it provides the problem statement, sample inputs/outputs, and time/memory limits. It then walks through designing algorithms, implementing solutions in C++, Java and Python, testing for errors, and submitting to Coursera for grading. For the pairwise product, a faster O(n) algorithm is presented after the initial O(n^2) solution fails due to timeout. Debugging and improving the fast algorithm is also demonstrated.
Skyler Motors Pvt Ltd plans to introduce an affordable electric car called Skyler that costs Rs. 100,000. The car will be fuel efficient at 26 km/liter and meet emission standards. It will be smaller in size with cost-cutting features like manual windows and no airbags to achieve its low price point. Skyler aims to target middle-income families and provide an alternative to scooters. It will be manufactured in Pakistan and have 3 variants priced from Rs. 150,000 to Rs. 210,000. Skyler expects to become profitable in its first 3 years of operation through strong marketing and securing financing options for customers.
The document provides details on the marketing strategy of the Tata Nano vehicle. It discusses the idea generation and history of Tata Motors, specifications and features of the Nano, its competitive pricing of 100,000 rupees, promotion through publicity and social media, distribution through dealerships, strengths like low price and weaknesses like small size, and post-purchase service plans. The conclusion is that the Nano has the potential to become not just India's future car but a global car if exported successfully.
This document discusses three Honda products - the Activa scooter, Unicorn motorcycle, and CB 1000R motorcycle. It provides details on each product like launch year, key features, pricing strategy used, and promotional activities. For the Activa, it mentions the first scooter launched by Honda in India in 2001. For the Unicorn, it highlights the mono-suspension design. And for the CB 1000R, it focuses on the powerful engine and transmission system.
Atlas Honda is a joint venture between Atlas Group and Honda Motors established in 1987. It manufactures and markets Honda motorcycles in Pakistan. The company has two production plants in Karachi and Sheikhupura with a daily production capacity of 400 and 1650 motorcycles respectively. Atlas Honda utilizes an SAP system to manage its supply chain, including production planning, manufacturing, warehousing, vendors, and transportation. Key functions include master production scheduling to anticipate shortages, vendor improvement programs, and hiring local contractors to transport parts between plants. The company aims to meet quality standards and customer satisfaction through continuous technology induction in its strategic goals.
This document provides an analysis of product development for Amul. It begins with an acknowledgement and introduction. It then discusses the dairy processing industry and major players in India. The document provides an overview of Amul, including its founding, achievements, and wide range of dairy products. It analyzes Amul's major competitors and concludes with a discussion of promoting its new product, Amul Pro.
Toyota is the second largest automaker globally but is also the most profitable, with 51 manufacturing companies across 26 countries producing a new vehicle every 6 seconds under its Toyota, Lexus, and Scion brands. Toyota has also diversified its business beyond automotive to include industries like housing, marine, telecommunications, and biotechnology. The company's success is largely attributed to its implementation of the Toyota Production System for efficient manufacturing operations.
Business analytics uses statistical analysis of a company's data to gain insights and make data-driven decisions. It aims to identify useful datasets and increase revenue, productivity, and efficiency. Examples of using analytics in business include churn prevention to identify at-risk customers, e-commerce personalization to increase sales, predictive maintenance to avoid downtime, insurance fraud detection to save billions, and automated candidate placement to improve hiring.
Skyler Motors Pvt Ltd plans to introduce an affordable electric car called Skyler that costs Rs. 100,000. The car will be fuel efficient at 26 km/liter and meet emission standards. It will be smaller in size with cost-cutting features like manual windows and no airbags to achieve its low price point. Skyler aims to target middle-income families and provide an alternative to scooters. It will be manufactured in Pakistan and have 3 variants priced from Rs. 150,000 to Rs. 210,000. Skyler expects to become profitable in its first 3 years of operation through strong marketing and securing financing options for customers.
The document provides details on the marketing strategy of the Tata Nano vehicle. It discusses the idea generation and history of Tata Motors, specifications and features of the Nano, its competitive pricing of 100,000 rupees, promotion through publicity and social media, distribution through dealerships, strengths like low price and weaknesses like small size, and post-purchase service plans. The conclusion is that the Nano has the potential to become not just India's future car but a global car if exported successfully.
This document discusses three Honda products - the Activa scooter, Unicorn motorcycle, and CB 1000R motorcycle. It provides details on each product like launch year, key features, pricing strategy used, and promotional activities. For the Activa, it mentions the first scooter launched by Honda in India in 2001. For the Unicorn, it highlights the mono-suspension design. And for the CB 1000R, it focuses on the powerful engine and transmission system.
Atlas Honda is a joint venture between Atlas Group and Honda Motors established in 1987. It manufactures and markets Honda motorcycles in Pakistan. The company has two production plants in Karachi and Sheikhupura with a daily production capacity of 400 and 1650 motorcycles respectively. Atlas Honda utilizes an SAP system to manage its supply chain, including production planning, manufacturing, warehousing, vendors, and transportation. Key functions include master production scheduling to anticipate shortages, vendor improvement programs, and hiring local contractors to transport parts between plants. The company aims to meet quality standards and customer satisfaction through continuous technology induction in its strategic goals.
This document provides an analysis of product development for Amul. It begins with an acknowledgement and introduction. It then discusses the dairy processing industry and major players in India. The document provides an overview of Amul, including its founding, achievements, and wide range of dairy products. It analyzes Amul's major competitors and concludes with a discussion of promoting its new product, Amul Pro.
Toyota is the second largest automaker globally but is also the most profitable, with 51 manufacturing companies across 26 countries producing a new vehicle every 6 seconds under its Toyota, Lexus, and Scion brands. Toyota has also diversified its business beyond automotive to include industries like housing, marine, telecommunications, and biotechnology. The company's success is largely attributed to its implementation of the Toyota Production System for efficient manufacturing operations.
Business analytics uses statistical analysis of a company's data to gain insights and make data-driven decisions. It aims to identify useful datasets and increase revenue, productivity, and efficiency. Examples of using analytics in business include churn prevention to identify at-risk customers, e-commerce personalization to increase sales, predictive maintenance to avoid downtime, insurance fraud detection to save billions, and automated candidate placement to improve hiring.
The document provides an executive summary and introduction to a market survey report on electric bikes (e-bikes) in Pune City, India. The summary includes:
1) The report is based on a survey of people in Sinhgad road and karve road areas of Pune to understand awareness and perceptions of e-bikes and factors influencing e-bike purchases.
2) Primary data was collected through questionnaires distributed to shops and the public to analyze awareness levels and purchase factors using statistical tools like SPSS.
3) The analysis concluded that customers would purchase e-bikes if their speed and power matched gasoline bikes and maintenance costs were reasonable.
Failure mode and effects analysis (FMEA) is a method to identify potential failures, determine their causes and effects, prioritize risks, and identify actions to address high-priority risks. An FMEA involves assembling a cross-functional team to analyze a process, product or service by identifying functions, potential failure modes and effects, causes, controls, severity, occurrence, detection ratings and risk priority numbers to prioritize improvement actions. FMEAs are used throughout a product or service lifecycle to prevent and reduce failures and risks.
Maruti Udyog Limited (MUL) was established in 1981 through an Act of Parliament to meet the growing demand for personal transportation due to a lack of public transportation in India. MUL's strategy was to offer compact, modern, and fuel-efficient vehicles. MUL released its first Maruti 800 car in 1983, which became very popular and made MUL the market leader. Due to increased competition, MUL now focuses on innovative marketing strategies and upgrading manufacturing facilities to counter competitors.
Maruti Suzuki has a physical distribution network to supply its finished vehicles from production to consumers. It uses multiple channel levels - including direct marketing, one level channels through retailers, and two level channels using wholesalers and retailers. The goals of Maruti's distribution channel design are to select the best places to display products, maintain a good environment for display, employ trained staff, and continuously assess and improve the retail channel. Maruti's physical distribution system aims to efficiently manage the supply chain from production to delivery.
This document provides an overview of Mahindra Logistics and its services. Some key points:
- Mahindra Logistics was established in 2000 as a strategic initiative of Mahindra & Mahindra to expand beyond product sales into logistics services.
- It now has over 1700 employees, 1600+ vehicles, and provides end-to-end logistics solutions to over 155 corporate customers across multiple industries like automotive, retail, pharma and more.
- The vision is to be the lead logistics provider for select industry segments. Services include supply chain management, transportation, warehousing, people movement and more.
- Case studies provided show solutions implemented for customers in retail and automotive industries.
This document discusses information about Atlas Honda Limited, a motorcycle manufacturer in Pakistan. It provides details about the group members, production capacity of 1600 motorcycles per day across two plants, financial contributions to the national exchequer, and awards won for best corporate reporting. It also outlines challenges faced such as competition and input costs, as well as competitors in the motorcycle market. For the year 2007-08, the company saw sales revenue growth of 23.37% despite a slight drop in gross profit margin due to rising material and utility costs. Operating expenses also increased in line with higher sales and new product launches.
The cause and effect diagram, also known as a fishbone diagram or Ishikawa diagram, was invented in 1943 by Kaoru Ishikawa to help identify potential causes for a problem. It maps out causes in categories related to a problem or effect. The major purpose is to generate a comprehensive list of possible causes through brainstorming to help understand and solve problems. To create one, the effect is written and main categories of causes are connected. Then detailed potential causes are added as branches in each category. Variations include diagrams for production processes or listing causes before structuring them in the diagram.
Marketing plan for maruti suzuki kizashi by rakesh shah ssRakesh Shah
Maruti Suzuki plans to launch the Kizashi luxury sedan in India in 2011. It will be available in two transmission options priced at INR 16.5-17.5 lakh. The marketing strategy involves positioning the Kizashi as a sporty sedan that delivers value. An advertising budget of INR 8 crores is allocated, with campaigns during the 2011 Cricket World Cup to promote the Kizashi and drive pre-bookings starting in February 2011.
This document discusses Amul's branding strategy for its ice cream product. It summarizes Amul's challenges entering the ice cream market late against established competitors. Amul's agency conducted research and discovered consumers saw ice cream as an occasional treat, not everyday food. Amul positioned its ice cream as "Real Milk, Real Ice Cream" to change this perception by emphasizing its high milk content. This communication strategy, along with pricing and distribution changes, helped Amul become the market leader in the Indian ice cream industry.
The document is a marketing report submitted to Ms. Samiya Hameed on Principles of Marketing for Pak Suzuki Motors (Pvt) Ltd. It includes an acknowledgement, executive summary, company introduction, milestones, SWOT analysis, segmentation, industry overview, marketing mix, environment analysis, and recommendations. The report provides a strategic analysis of Pak Suzuki Motors covering various aspects of their business and marketing strategies.
This document is a project report submitted by Aman Bharti on the Production Part Approval Process (PPAP) during his internship at Maruti Suzuki India Limited. It includes an introduction to the company, details about the Quality Assurance and Part Quality department where he worked, and an explanation of the PPAP process. The PPAP process ensures that parts meet all customer requirements before production. The report outlines the various documents and processes required as part of a PPAP submission, including a design record, engineering drawings, process flow diagrams, and production part samples.
Honda was founded in 1948 by Soichiro Honda as a motorcycle manufacturer. It has since expanded to become a major manufacturer of automobiles, motorcycles, engines, and robots. The presentation provides an overview of Honda's history, leadership, products, worldwide presence, quality objectives, and promotional strategies. It highlights Honda's focus on fuel efficiency and environmental friendliness.
A project report on consumer satisfaction level of bajaj bike project reportBabasab Patil
This document provides an executive summary and introduction to a study about customer satisfaction with Bajaj PLATINA bikes in Ilkal town. The summary includes:
1) An overview of the objectives, scope, methodology and findings of the customer satisfaction study, which was conducted through a survey of 100 customers.
2) Background information on Bajaj Auto, the largest manufacturer of 2 and 3-wheelers in India, and its dominant shares of various vehicle segments.
3) Details about the industrial profile of 2-wheeler manufacturers in India and characteristics of the market.
Honda was founded in 1948 by Japanese mechanic Soichiro Honda. It exported its first car, the N600, to the United States in 1970. Honda is now a major global automaker with production facilities worldwide. Its lineup includes popular models like the Fit, Civic, Accord, Odyssey, and CR-V. Honda focuses on research and development to provide customers with fuel efficient and advanced technology vehicles. It employs over 167,000 people across 134 production facilities and 31 R&D centers globally.
The automobile industry in India is one of the largest in the world and fastest growing, manufacturing over 3.23 million units in 2012-13 and expected to reach 10 million units by 2020-21. India also emerged as the fourth largest exporter of automobiles in 2009. Some major players in the industry include Maruti Suzuki, Tata Motors, and Hero MotoCorp. Maruti Suzuki leads the industry with a 45% market share in passenger vehicles. Tata Motors is India's largest automobile company and the world's fifth largest truck manufacturer. Hero MotoCorp was formed in 2011 from the previous Hero Honda joint venture between Hero Group and Honda and has a 59% market share in motorcycles. The future
This document provides an overview of Honda Motorcycle and Scooter India Pvt. Ltd (HMSI). It discusses HMSI's growth, production facilities, product lineup, objectives of the project to assess customer satisfaction and purchase influencing factors of Honda bikes in India. Technical specifications are provided for popular Honda motorcycles and scooters like Activa, Dio, Unicorn, Shine, Aviator and Dream Yuga.
This document provides information about Amul butter, including its marketing mix strategies. Some key points:
- Amul butter has been the market leader in India for over 4 decades, with a current 88% market share.
- Amul follows a customer-based brand identity model to build emotional connections. Its mascot of the Amul girl aims to make the brand appealing through humor and Indian culture.
- Its marketing mix includes establishing the product as a staple spread through innovative advertising campaigns. Distribution reaches both urban and rural areas nationwide.
- Historical sales data shows Amul's turnover growing steadily over the past 20 years, indicating its brand strength and market dominance in the butter category.
This document provides an overview of quality tools that can be used for continuous improvement. It outlines 7 basic quality tools - flow chart, cause and effect diagram, check sheet, histogram, Pareto chart, scatter diagram, and stratification. For each tool, it describes what the tool is, when it should be used, how to construct it, and provides an example. It also discusses using pivot tables instead of manual check sheets for summarizing large datasets. The agenda outlines using these tools to analyze processes and reports to deliver more important information instantly through transformation.
This document discusses algorithm design and problem solving. It covers topics like top-down modular design, structure diagrams, stepwise refinement, pseudocode, flowcharts, and validation checks. An example flowchart is provided that squares the first 5 numbers. Pseudocode is also demonstrated for an ATM algorithm. Key aspects of algorithm evaluation like efficiency, correctness, and appropriateness are defined. Various programming constructs like assignment statements, arithmetic and relational operators, and Boolean logic are also explained.
This document outlines an assignment to analyze and design a program for sequential control flow. The objectives are to understand computational problem solving, sequential logic, and how to create IPO charts, algorithms, and flow charts. As an example, students are instructed to create these analysis tools to solve a temperature conversion problem that takes Celsius input and outputs Fahrenheit and Kelvin scales using defined formulas. The document provides background on problem solving techniques, sequential control flow, and common analysis tools like IPO charts, algorithms using pseudocode, and flow charts using standard symbols.
The document provides an executive summary and introduction to a market survey report on electric bikes (e-bikes) in Pune City, India. The summary includes:
1) The report is based on a survey of people in Sinhgad road and karve road areas of Pune to understand awareness and perceptions of e-bikes and factors influencing e-bike purchases.
2) Primary data was collected through questionnaires distributed to shops and the public to analyze awareness levels and purchase factors using statistical tools like SPSS.
3) The analysis concluded that customers would purchase e-bikes if their speed and power matched gasoline bikes and maintenance costs were reasonable.
Failure mode and effects analysis (FMEA) is a method to identify potential failures, determine their causes and effects, prioritize risks, and identify actions to address high-priority risks. An FMEA involves assembling a cross-functional team to analyze a process, product or service by identifying functions, potential failure modes and effects, causes, controls, severity, occurrence, detection ratings and risk priority numbers to prioritize improvement actions. FMEAs are used throughout a product or service lifecycle to prevent and reduce failures and risks.
Maruti Udyog Limited (MUL) was established in 1981 through an Act of Parliament to meet the growing demand for personal transportation due to a lack of public transportation in India. MUL's strategy was to offer compact, modern, and fuel-efficient vehicles. MUL released its first Maruti 800 car in 1983, which became very popular and made MUL the market leader. Due to increased competition, MUL now focuses on innovative marketing strategies and upgrading manufacturing facilities to counter competitors.
Maruti Suzuki has a physical distribution network to supply its finished vehicles from production to consumers. It uses multiple channel levels - including direct marketing, one level channels through retailers, and two level channels using wholesalers and retailers. The goals of Maruti's distribution channel design are to select the best places to display products, maintain a good environment for display, employ trained staff, and continuously assess and improve the retail channel. Maruti's physical distribution system aims to efficiently manage the supply chain from production to delivery.
This document provides an overview of Mahindra Logistics and its services. Some key points:
- Mahindra Logistics was established in 2000 as a strategic initiative of Mahindra & Mahindra to expand beyond product sales into logistics services.
- It now has over 1700 employees, 1600+ vehicles, and provides end-to-end logistics solutions to over 155 corporate customers across multiple industries like automotive, retail, pharma and more.
- The vision is to be the lead logistics provider for select industry segments. Services include supply chain management, transportation, warehousing, people movement and more.
- Case studies provided show solutions implemented for customers in retail and automotive industries.
This document discusses information about Atlas Honda Limited, a motorcycle manufacturer in Pakistan. It provides details about the group members, production capacity of 1600 motorcycles per day across two plants, financial contributions to the national exchequer, and awards won for best corporate reporting. It also outlines challenges faced such as competition and input costs, as well as competitors in the motorcycle market. For the year 2007-08, the company saw sales revenue growth of 23.37% despite a slight drop in gross profit margin due to rising material and utility costs. Operating expenses also increased in line with higher sales and new product launches.
The cause and effect diagram, also known as a fishbone diagram or Ishikawa diagram, was invented in 1943 by Kaoru Ishikawa to help identify potential causes for a problem. It maps out causes in categories related to a problem or effect. The major purpose is to generate a comprehensive list of possible causes through brainstorming to help understand and solve problems. To create one, the effect is written and main categories of causes are connected. Then detailed potential causes are added as branches in each category. Variations include diagrams for production processes or listing causes before structuring them in the diagram.
Marketing plan for maruti suzuki kizashi by rakesh shah ssRakesh Shah
Maruti Suzuki plans to launch the Kizashi luxury sedan in India in 2011. It will be available in two transmission options priced at INR 16.5-17.5 lakh. The marketing strategy involves positioning the Kizashi as a sporty sedan that delivers value. An advertising budget of INR 8 crores is allocated, with campaigns during the 2011 Cricket World Cup to promote the Kizashi and drive pre-bookings starting in February 2011.
This document discusses Amul's branding strategy for its ice cream product. It summarizes Amul's challenges entering the ice cream market late against established competitors. Amul's agency conducted research and discovered consumers saw ice cream as an occasional treat, not everyday food. Amul positioned its ice cream as "Real Milk, Real Ice Cream" to change this perception by emphasizing its high milk content. This communication strategy, along with pricing and distribution changes, helped Amul become the market leader in the Indian ice cream industry.
The document is a marketing report submitted to Ms. Samiya Hameed on Principles of Marketing for Pak Suzuki Motors (Pvt) Ltd. It includes an acknowledgement, executive summary, company introduction, milestones, SWOT analysis, segmentation, industry overview, marketing mix, environment analysis, and recommendations. The report provides a strategic analysis of Pak Suzuki Motors covering various aspects of their business and marketing strategies.
This document is a project report submitted by Aman Bharti on the Production Part Approval Process (PPAP) during his internship at Maruti Suzuki India Limited. It includes an introduction to the company, details about the Quality Assurance and Part Quality department where he worked, and an explanation of the PPAP process. The PPAP process ensures that parts meet all customer requirements before production. The report outlines the various documents and processes required as part of a PPAP submission, including a design record, engineering drawings, process flow diagrams, and production part samples.
Honda was founded in 1948 by Soichiro Honda as a motorcycle manufacturer. It has since expanded to become a major manufacturer of automobiles, motorcycles, engines, and robots. The presentation provides an overview of Honda's history, leadership, products, worldwide presence, quality objectives, and promotional strategies. It highlights Honda's focus on fuel efficiency and environmental friendliness.
A project report on consumer satisfaction level of bajaj bike project reportBabasab Patil
This document provides an executive summary and introduction to a study about customer satisfaction with Bajaj PLATINA bikes in Ilkal town. The summary includes:
1) An overview of the objectives, scope, methodology and findings of the customer satisfaction study, which was conducted through a survey of 100 customers.
2) Background information on Bajaj Auto, the largest manufacturer of 2 and 3-wheelers in India, and its dominant shares of various vehicle segments.
3) Details about the industrial profile of 2-wheeler manufacturers in India and characteristics of the market.
Honda was founded in 1948 by Japanese mechanic Soichiro Honda. It exported its first car, the N600, to the United States in 1970. Honda is now a major global automaker with production facilities worldwide. Its lineup includes popular models like the Fit, Civic, Accord, Odyssey, and CR-V. Honda focuses on research and development to provide customers with fuel efficient and advanced technology vehicles. It employs over 167,000 people across 134 production facilities and 31 R&D centers globally.
The automobile industry in India is one of the largest in the world and fastest growing, manufacturing over 3.23 million units in 2012-13 and expected to reach 10 million units by 2020-21. India also emerged as the fourth largest exporter of automobiles in 2009. Some major players in the industry include Maruti Suzuki, Tata Motors, and Hero MotoCorp. Maruti Suzuki leads the industry with a 45% market share in passenger vehicles. Tata Motors is India's largest automobile company and the world's fifth largest truck manufacturer. Hero MotoCorp was formed in 2011 from the previous Hero Honda joint venture between Hero Group and Honda and has a 59% market share in motorcycles. The future
This document provides an overview of Honda Motorcycle and Scooter India Pvt. Ltd (HMSI). It discusses HMSI's growth, production facilities, product lineup, objectives of the project to assess customer satisfaction and purchase influencing factors of Honda bikes in India. Technical specifications are provided for popular Honda motorcycles and scooters like Activa, Dio, Unicorn, Shine, Aviator and Dream Yuga.
This document provides information about Amul butter, including its marketing mix strategies. Some key points:
- Amul butter has been the market leader in India for over 4 decades, with a current 88% market share.
- Amul follows a customer-based brand identity model to build emotional connections. Its mascot of the Amul girl aims to make the brand appealing through humor and Indian culture.
- Its marketing mix includes establishing the product as a staple spread through innovative advertising campaigns. Distribution reaches both urban and rural areas nationwide.
- Historical sales data shows Amul's turnover growing steadily over the past 20 years, indicating its brand strength and market dominance in the butter category.
This document provides an overview of quality tools that can be used for continuous improvement. It outlines 7 basic quality tools - flow chart, cause and effect diagram, check sheet, histogram, Pareto chart, scatter diagram, and stratification. For each tool, it describes what the tool is, when it should be used, how to construct it, and provides an example. It also discusses using pivot tables instead of manual check sheets for summarizing large datasets. The agenda outlines using these tools to analyze processes and reports to deliver more important information instantly through transformation.
This document discusses algorithm design and problem solving. It covers topics like top-down modular design, structure diagrams, stepwise refinement, pseudocode, flowcharts, and validation checks. An example flowchart is provided that squares the first 5 numbers. Pseudocode is also demonstrated for an ATM algorithm. Key aspects of algorithm evaluation like efficiency, correctness, and appropriateness are defined. Various programming constructs like assignment statements, arithmetic and relational operators, and Boolean logic are also explained.
This document outlines an assignment to analyze and design a program for sequential control flow. The objectives are to understand computational problem solving, sequential logic, and how to create IPO charts, algorithms, and flow charts. As an example, students are instructed to create these analysis tools to solve a temperature conversion problem that takes Celsius input and outputs Fahrenheit and Kelvin scales using defined formulas. The document provides background on problem solving techniques, sequential control flow, and common analysis tools like IPO charts, algorithms using pseudocode, and flow charts using standard symbols.
This document discusses algorithms and flowcharts. It defines an algorithm as a set of steps to solve a problem, especially by a computer. Algorithms have inputs, outputs, and must be unambiguous, finite, effective, and language-independent. Flowcharts provide a graphical representation of algorithms using standard symbols connected by arrows to show the flow. The document gives examples of algorithms to add two numbers and provides a flowchart to multiply two numbers as illustrations.
Here are the steps to solve the problems using IPO table, pseudo code and flowchart:
1. Define the problem and understand requirements
2. Make IPO table:
- Input, Process, Output
3. Write pseudo code using proper indentation and comments
4. Draw flowchart using standard symbols
5. Test and debug the program
This systematic approach helps analyze the problem, design the algorithm and implement it properly. The key is breaking down the problem into smaller understandable steps.
The document discusses algorithms and flowcharts. It defines an algorithm as a finite set of steps to solve a problem and notes that algorithms can be expressed in various ways, including pseudocode and flowcharts. Pseudocode uses a language similar to programming but without specific syntax, making it readable by programmers familiar with different languages. A flowchart provides a graphical representation of an algorithm's logical flow. The document provides examples of algorithms expressed in pseudocode and represented through flowcharts, such as finding the average of two numbers and calculating the largest of several inputs. It also discusses common flowchart structures like sequence, selection, and iteration.
This document contains lecture notes on error handling in Visual Basic .NET. It discusses the different types of errors that can occur, including syntax errors, logical errors, and run-time errors. It introduces exception handling in VB.NET using Try/Catch blocks to trap errors. Specific exception classes are described that can be used to trap different error types. Finally, it discusses using the Throw statement to raise custom exceptions. The notes provide an overview of using exceptions to prevent programs from crashing and make them more robust.
This document contains solutions to a midterm exam for a software engineering course. It provides answers to 17 questions about topics like version control, testing, metrics, refactoring, and object-oriented design. Code examples are included and analyzed for code smells. The document aims to test students' understanding of key software engineering principles and best practices covered in the course.
This document outlines the syllabus for the subject "Design and Analysis of Algorithms" for the 3rd year 1st semester students of the Computer Science and Engineering department with specialization in Cyber Security at CMR Engineering College.
The syllabus is divided into 5 units which cover topics like algorithm analysis, asymptotic notations, algorithm design techniques like divide and conquer, dynamic programming, greedy algorithms etc. It also discusses NP-hard and NP-complete problems. The document provides the textbook and references for the subject. It further includes introductions to different units explaining key concepts like algorithms, properties of algorithms, ways to represent algorithms, need for algorithm analysis etc.
Introduction to Design Algorithm And Analysis.pptBhargaviDalal4
This document contains the syllabus for the subject "Design and Analysis of Algorithms" for the 3rd year 1st semester students of CMR Engineering College. It includes 5 units - Introduction, Disjoint Sets and Backtracking, Dynamic Programming and Greedy Methods, Branch and Bound, and NP-Hard and NP-Complete problems. The introduction covers topics like algorithm complexity analysis and divide and conquer algorithms. The syllabus outlines core algorithms topics and applications like binary search, quicksort, dynamic programming, shortest paths, knapsack etc. that will be covered in the course.
The document discusses problem solving in computer science and algorithms. It defines an algorithm as a clearly defined set of steps to solve a problem. Key characteristics of algorithms are that they are unambiguous, have well-defined inputs and outputs, terminate in a finite number of steps, and are independent of programming languages. Examples of algorithms that find the largest number among three inputs and calculate a factorial are provided. The document also discusses sorting problems and examples of problems solved by algorithms like the human genome project, internet routing, and electronic commerce.
The document introduces algorithms and their role in computing. It defines computational problems as relationships between inputs and outputs. Algorithms are tools used to solve well-specified computational problems and must be correct and efficient. Examples of algorithms are given for common problems like determining if a number is prime or sorting a list alphabetically. Key aspects of algorithms like variables, instructions, selection, repetition and documentation are outlined. Examples are provided of analyzing algorithm efficiency based on runtime. Pseudo-code conventions for writing algorithms are also presented.
CP4151 ADSA unit1 Advanced Data Structures and AlgorithmsSheba41
The document introduces algorithms and their role in computing. It defines computational problems as relationships between inputs and outputs. Algorithms are tools used to solve well-specified computational problems and must be correct and efficient. Examples of algorithms are provided, along with their components like variables, instructions, selections, and repetitions. The document also discusses algorithm efficiency and provides examples comparing the efficiencies of different sorting algorithms. Pseudo-code conventions for writing algorithms are also outlined.
This document discusses the problem solving process in programming. It describes the three main phases: analyzing the problem, designing an algorithm to solve it, and implementing the algorithm in code. In the analysis phase, the problem and requirements are outlined, and a flowchart or pseudocode is used to design the algorithm. In the implementation phase, the algorithm is coded into a program. Finally, the program is tested to verify it works correctly and identify any errors. The key steps of each phase are explained in detail with examples.
This document discusses complexity analysis of algorithms. It defines an algorithm and lists properties like being correct, unambiguous, terminating, and simple. It describes common algorithm design techniques like divide and conquer, dynamic programming, greedy method, and backtracking. It compares divide and conquer with dynamic programming. It discusses algorithm analysis in terms of time and space complexity to predict resource usage and compare algorithms. It introduces asymptotic notations like Big-O notation to describe upper bounds of algorithms as input size increases.
This document discusses algorithms and how to create good algorithms. It defines an algorithm as a step-by-step procedure to solve a problem. It lists properties of good algorithms as being simple, complete, correct, with appropriate abstraction and precision. The document provides examples of algorithms using pseudocode and discusses different types of algorithms like sequence, decision, and repetition. It also outlines the steps to create an algorithm as analyzing the problem, designing a solution, implementing the program, testing it, and validating it works under all circumstances.
01 Introduction to analysis of Algorithms.pptxssuser586772
An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks.
An algorithm is an efficient method that can be expressed within finite amount of Time and space.
The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. To Evaluate An Algorithm we have to Satisfy the following Criteria:
INPUT: The Algorithm should be given zero or more input.
OUTPUT: At least one quantity is produced. For each input the algorithm produced value from specific task.
DEFINITENESS: Each instruction is clear and unambiguous.
FINITENESS: If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps.
EFFECTIVENESS: Every instruction must very basic so that it can be carried out, in principle, by a person using only pencil & paper.Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem.
Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language.
Program : It is exact code written for problem following all the rules of the programming language.Algorithm can be described (Represent) in four ways.
Natural language like English:
When this way is chooses, care should be taken, we
should ensure that each & every statement is definite.
(no ambiguity)
2. Graphic representation called flowchart:
This method will work well when the algorithm is small& simple.
3. Pseudo-code Method:
In this method, we should typically describe algorithms as
program, which resembles language like Pascal & Algol
(Algorithmic Language).
4.Programming Language:
we have to use programming language to write algorithms like
C, C++,JAVA etc.Comments begin with // and continue until the end of line.
Blocks are indicated with matching braces { and }.
An identifier begins with a letter. The data types of variables are not explicitly declared.
node= record
{
data type 1 data 1;
data type n data n;
node *link;
}
4. There are two Boolean values TRUE and FALSE.
Logical Operators
AND, OR, NOT
Relational Operators
<, <=,>,>=, =, !=
1.How to create an algorithm: To create an algorithm we have following design technique
a) Divide & Conquer
b) Greedy method
c) Dynamic Programming
d) Branch & Bound
e) Backtracking
2.How to validate an algorithm:
Once an algorithm is created it is necessary to show that it computes the correct Pr
This document provides an introduction to algorithms including definitions, characteristics, and the design process. It defines an algorithm as a finite set of unambiguous instructions to solve a problem. Key points:
- Algorithms must have input, output, be definitive, finite, and effective.
- The design process includes understanding the problem, developing a solution algorithm, proving correctness, analyzing efficiency, and coding.
- Examples of algorithm types are approximate, probabilistic, infinite, and heuristic.
- Pseudocode is commonly used to specify algorithms more clearly than natural language alone.
This document provides sample code and exercises for learning C++. It covers writing "Hello World" programs, calculating basic statistics, finding prime numbers, working with loops, and debugging a factorial program. The exercises are divided into sections like writing different "Hello World" programs, understanding scope, using conditionals and loops, and fixing errors in a factorial function. Students are instructed to complete the exercises by writing code in separate files and submitting their work.
A review on techniques and modelling methodologies used for checking electrom...nooriasukmaningtyas
The proper function of the integrated circuit (IC) in an inhibiting electromagnetic environment has always been a serious concern throughout the decades of revolution in the world of electronics, from disjunct devices to today’s integrated circuit technology, where billions of transistors are combined on a single chip. The automotive industry and smart vehicles in particular, are confronting design issues such as being prone to electromagnetic interference (EMI). Electronic control devices calculate incorrect outputs because of EMI and sensors give misleading values which can prove fatal in case of automotives. In this paper, the authors have non exhaustively tried to review research work concerned with the investigation of EMI in ICs and prediction of this EMI using various modelling methodologies and measurement setups.
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
3. To introduce you to our automated grading system, we will discuss
two simple programming challenges and walk you through a step-by-step
process of solving them. We will encounter several common pitfalls and
will show you how to fix them.
Below is a brief overview of what it takes to solve a programming chal-
lenge in five steps:
Reading problem statement. The problem statement specifies the input-
output format, the constraints for the input data as well as time and
memory limits. Your goal is to implement a fast program that solves
the problem and works within the time and memory limits.
Designing an algorithm. When the problem statement is clear, start de-
signing an algorithm and don’t forget to prove that it works correctly.
Implementing an algorithm. After you developed an algorithm, start
implementing it in a programming language of your choice.
Testing and debugging your program. Testing is the art of revealing
bugs. Debugging is the art of exterminating the bugs. When your
program is ready, start testing it! If a bug is found, fix it and test
again.
Submitting your program to the grading system. After testing and de-
bugging your program, submit it to the grading system and wait for
the message “Good job!”. In the case you see a different message,
return back to the previous stage.
3
4. 1 Sum of Two Digits
Sum of Two Digits Problem
Compute the sum of two single digit numbers.
Input: Two single digit numbers.
Output: The sum of these num-
bers.
2 + 3 = 5
We start from this ridiculously simple problem to show you the
pipeline of reading the problem statement, designing an algorithm, im-
plementing it, testing and debugging your program, and submitting it to
the grading system.
Input format. Integers a and b on the same line (separated by a space).
Output format. The sum of a and b.
Constraints. 0 ≤ a,b ≤ 9.
Sample.
Input:
9 7
Output:
16
Time limits (sec.):
C C++ Java Python C# Haskell JavaScript Kotlin Ruby Rust Scala
1 1 1.5 5 1.5 2 5 1.5 5 1 3
Memory limit. 512 Mb.
4
5. 1.1 Implementing an Algorithm
For this trivial problem, we will skip “Designing an algorithm” step and
will move right to the pseudocode.
SumOfTwoDigits(a, b):
return a + b
Since the pseudocode does not specify how we input a and b, below we
provide solutions in C++, Java, and Python3 programming languages as
well as recommendations on compiling and running them. You can copy-
and-paste the code to a file, compile/run it, test it on a few datasets, and
then submit (the source file, not the compiled executable) to the grading
system. Needless to say, we assume that you know the basics of one of
programming languages that we use in our grading system.
C++
#include <iostream>
int sum_of_digits(int first_digit, int second_digit) {
return first_digit + second_digit;
}
int main() {
int a = 0;
int b = 0;
std::cin >> a;
std::cin >> b;
std::cout << sum_of_digits(a, b);
return 0;
}
Save this to a file (say, aplusb.cpp), compile it, run the resulting
executable, and enter two numbers (on the same line).
5
6. Java
import java.util.Scanner;
class SumOfDigits {
static int sumOfDigits(int first_digit, int second_digit) {
return first_digit + second_digit;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
System.out.println(sumOfDigits(a, b));
}
}
Save this to a file SumOfDigits.java, compile it, run the resulting
executable, and enter two numbers (on the same line).
Python3
# python3
def sum_of_digits(first_digit, second_digit):
return first_digit + second_digit
if __name__ == ’__main__’:
a, b = map(int, input().split())
print(sum_of_digits(a, b))
Save this to a file (say, aplusb.py), run it, and enter two numbers
on the same line. (The first line in the code above tells the grading
system to use Python3 rather Python2.)
Your goal is to implement an algorithm that produces a correct result
under the given time and memory limits for any input satisfying the given
constraints. You do not need to check that the input data satisfies the
constraints, e.g., for the Sum of Two Digits Problem you do not need to
check that the given integers a and b are indeed single digit integers (this
is guaranteed).
6
7. 1.2 Submitting to the Grading System at Coursera
This is what a fresh submission page looks like:
The blue bubble suggests you to read a general information about pro-
gramming assignments. We encourage you to read it if you haven’t solved
programming assignments before.
The line above the bubble indicates that there are two programming
challenges in this assignment. To pass this assignment, you need to solve
both programming challenges. This should not be difficult as in this docu-
ment we give detailed instructions for solving them. For all the remaining
programming assignments, the passing threshold is usually around 50%.
To pass the course, you need to pass all the programming assignments.
The line below the blue bubble indicates the deadline for this assign-
ment. Please not that this is a suggestion rather than a hard deadline. If
you miss a deadline, you may safely switch to the next session of the course
(a new session starts automatically every two weeks). All your progress
will be transferred to the new session in this case. See Coursera help arti-
cle on switching sessions.
At the right, there is a link to the discussion forum attached to this as-
signment. We encourage you to visit the forum on a regular basis to ask
7
8. questions and to help other learners. Note also that for each program-
ming challenge, there is a separate thread at the forum. The link to this
particular thread can be found at the end of the programming challenge
statement.
When you are ready to submit a solution to a programming challenge,
go the the “My submission” tab that looks as follows:
Click on the “Create submission” button. The page now looks as follows.
In this particular assignment, there are two programming challenges (Sum
8
9. of Two Digits and Maximum Pairwise Product). Click on a challenge you
want to submit, upload a source file (rather than executable) of your solu-
tion, and press the “Submit” button. The page now looks as follows:
You may safely leave the page while your solution is being graded (in most
cases, it is done in less than a minute, but when the servers are overloaded
it may take several minutes; please be patient). When the grading is done,
the submission page will look like this:
In this particular case, it says that the first programming challenge is
passed (score is 1/1) but the whole programming assignment is not passed
yet (since one needs to pass both programming challenges for this).
9
10. 2 Maximum Pairwise Product
Maximum Pairwise Product Problem
Find the maximum product of two distinct num-
bers in a sequence of non-negative integers.
Input: A sequence of non-negative
integers.
Output: The maximum value that
can be obtained by multiplying
two different elements from the se-
quence.
5 6 2 7 4
5 30 10 35 20
6 30 12 42 24
2 10 12 14 8
7 35 42 14 28
4 20 24 8 28
Given a sequence of non-negative integers a1,...,an, compute
max
1≤i,j≤n
ai · aj .
Note that i and j should be different, though it may be the case that ai = aj.
Input format. The first line contains an integer n. The next line contains
n non-negative integers a1,...,an (separated by spaces).
Output format. The maximum pairwise product.
Constraints. 2 ≤ n ≤ 2 · 105; 0 ≤ a1,...,an ≤ 2 · 105.
Sample 1.
Input:
3
1 2 3
Output:
6
10
11. Sample 2.
Input:
10
7 5 14 2 8 8 10 1 2 3
Output:
140
Time and memory limits. The same as for the previous problem.
2.1 Naive Algorithm
A naive way to solve the Maximum Pairwise Product Problem is to go
through all possible pairs of the input elements A[1...n] = [a1,...,an] and
to find a pair of distinct elements with the largest product:
MaxPairwiseProductNaive(A[1...n]):
product ← 0
for i from 1 to n:
for j from 1 to n:
if i , j:
if product < A[i] · A[j]:
product ← A[i] · A[j]
return product
This code can be optimized and made more compact as follows.
MaxPairwiseProductNaive(A[1...n]):
product ← 0
for i from 1 to n:
for j from i + 1 to n:
product ← max(product,A[i] · A[j])
return product
Implement this algorithm in your favorite programming language. If
you are using C++, Java, or Python3, you may want to download the starter
files (we provide starter solutions in these three languages for all the prob-
lems in the book). For other languages, you need to implement your solu-
tion from scratch.
11
12. Starter solutions for C++, Java, and Python3 are shown below.
C++
#include <iostream>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
using std::max;
int MaxPairwiseProduct(const vector<int>& numbers) {
int product = 0;
int n = numbers.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
product = max(product, numbers[i] * numbers[j]);
}
}
return product;
}
int main() {
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}
int product = MaxPairwiseProduct(numbers);
cout << product << "n";
return 0;
}
Java
import java.util.*;
import java.io.*;
12
13. public class MaxPairwiseProduct {
static int getMaxPairwiseProduct(int[] numbers) {
int product = 0;
int n = numbers.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
product = Math.max(product,
numbers[i] * numbers[j]);
}
}
return product;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println(getMaxPairwiseProduct(numbers));
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new
InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
13
14. st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
Python
# Uses python3
n = int(input())
a = [int(x) for x in input().split()]
product = 0
for i in range(n):
for j in range(i + 1, n):
product = max(product, a[i] * a[j])
print(product)
After submitting this solution to the grading system, many students
are surprised when they see the following message:
Failed case #4/17: time limit exceeded
After you submit your program, we test it on dozens of carefully de-
signed test cases to make sure the program is fast and error proof. As the
result, we usually know what kind of errors you made. The message above
tells that the submitted program exceeds the time limit on the 4th out of
17 test cases.
Stop and Think. Why does the solution not fit into the time limit?
14
15. MaxPairwiseProductNaive performs of the order of n2 steps on a se-
quence of length n. For the maximal possible value n = 2 · 105, the
number of steps is of the order 4 · 1010. Since many modern com-
puters perform roughly 108–109 basic operations per second (this de-
pends on a machine, of course), it may take tens of seconds to execute
MaxPairwiseProductNaive, exceeding the time limit for the Maximum
Pairwise Product Problem.
We need a faster algorithm!
2.2 Fast Algorithm
In search of a faster algorithm, you play with small examples like
[5,6,2,7,4]. Eureka—it suffices to multiply the two largest elements of
the array—7 and 6!
Since we need to find the largest and the second largest elements, we
need only two scans of the sequence. During the first scan, we find the
largest element. During the second scan, we find the largest element
among the remaining ones by skipping the element found at the previ-
ous scan.
MaxPairwiseProductFast(A[1...n]):
index1 ← 1
for i from 2 to n:
if A[i] > A[index1]:
index1 ← i
index2 ← 1
for i from 2 to n:
if A[i] , A[index1] and A[i] > A[index2]:
index2 ← i
return A[index1] · A[index2]
2.3 Testing and Debugging
Implement this algorithm and test it using an input A = [1,2]. It will
output 2, as expected. Then, check the input A = [2,1]. Surprisingly, it
outputs 4. By inspecting the code, you find out that after the first loop,
index1 = 1. The algorithm then initializes index2 to 1 and index2 is never
15
16. updated by the second for loop. As a result, index1 = index2 before the
return statement. To ensure that this does not happen, you modify the
pseudocode as follows:
MaxPairwiseProductFast(A[1...n]):
index1 ← 1
for i from 2 to n:
if A[i] > A[index1]:
index1 ← i
if index1 = 1:
index2 ← 2
else:
index2 ← 1
for i from 1 to n:
if A[i] , A[index1] and A[i] > A[index2]:
index2 ← i
return A[index1] · A[index2]
Check this code on a small datasets [7,4,5,6] to ensure that it produces
correct results. Then try an input
2
100000 90000
You may find out that the program outputs something like 410065408 or
even a negative number instead of the correct result 9000000000. If it
does, this is most probably caused by an integer overflow. For example, in
C++ programming language a large number like 9000000000 does not fit
into the standard int type that on most modern machines occupies 4 bytes
and ranges from −231 to 231 − 1, where
231
= 2147483648.
Hence, instead of using the C++ int type you need to use the int64 t type
when computing the product and storing the result. This will prevent
integer overflow as the int64 t type occupies 8 bytes and ranges from
−263 to 263 − 1, where
263
= 9223372036854775808.
16
17. You then proceed to testing your program on large data sets, e.g., an
array A[1...2·105], where A[i] = i for all 1 ≤ i ≤ 2·105. There are two ways
of doing this.
1. Create this array in your program and pass it to
MaxPairwiseProductFast (instead of reading it from the stan-
dard input).
2. Create a separate program, that writes such an array to a file
dataset.txt. Then pass this dataset to your program from console
as follows:
yourprogram < dataset.txt
Check that your program processes this dataset within time limit and re-
turns the correct result: 39999800000. You are now confident that the
program finally works!
However, after submitting it to the testing system, it fails again...
Failed case #5/17: wrong answer
But how would you generate a test case that make your program fail and
help you to figure out what went wrong?
2.4 Can You Tell Me What Error Have I Made?
You are probably wondering why we did not provide you with the 5th out
of 17 test datasets that brought down your program. The reason is that
nobody will provide you with the test cases in real life!
Since even experienced programmers often make subtle mistakes solv-
ing algorithmic problems, it is important to learn how to catch bugs as
early as possible. When the authors of this book started to program, they
naively thought that nearly all their programs are correct. By now, we
know that our programs are almost never correct when we first run them.
When you are confident that your program works, you often test it on
just a few test cases, and if the answers look reasonable, you consider your
work done. However, this is a recipe for a disaster. To make your program
always work, you should test it on a set of carefully designed test cases.
Learning how to implement algorithms as well as test and debug your
programs will be invaluable in your future work as a programmer.
17
18. 2.5 Stress Testing
We will now introduce stress testing—a technique for generating thou-
sands of tests with the goal of finding a test case for which your solution
fails.
A stress test consists of four parts:
1. Your implementation of an algorithm.
2. An alternative, trivial and slow, but correct implementation of an
algorithm for the same problem.
3. A random test generator.
4. An infinite loop in which a new test is generated and fed into both
implementations to compare the results. If their results differ, the
test and both answers are output, and the program stops, otherwise
the loop repeats.
The idea behind stress testing is that two correct implementations
should give the same answer for each test (provided the answer to the
problem is unique). If, however, one of the implementations is incorrect,
then there exists a test on which their answers differ. The only case when
it is not so is when there is the same mistake in both implementations,
but that is unlikely (unless the mistake is somewhere in the input/output
routines which are common to both solutions). Indeed, if one solution is
correct and the other is wrong, then there exists a test case on which they
differ. If both are wrong, but the bugs are different, then most likely there
exists a test on which two solutions give different results.
Here is the the stress test for MaxPairwiseProductFast using
MaxPairwiseProductNaive as a trivial implementation:
18
19. StressTest(N,M):
while true:
n ← random integer between 2 and N
allocate array A[1...n]
for i from 1 to n:
A[i] ← random integer between 0 and M
print(A[1...n])
result1 ← MaxPairwiseProductNaive(A)
result2 ← MaxPairwiseProductFast(A)
if result1 = result2:
print(“OK”)
else:
print(“Wrong answer: ”, result1, result2)
return
The while loop above starts with generating the length of the input
sequence n, a random number between 2 and N. It is at least 2, because
the problem statement specifies that n ≥ 2. The parameter N should be
small enough to allow us to explore many tests despite the fact that one of
our solutions is slow.
After generating n, we generate an array A with n random numbers
from 0 to M and output it so that in the process of the infinite loop we
always know what is the current test; this will make it easier to catch an
error in the test generation code. We then call two algorithms on A and
compare the results. If the results are different, we print them and halt.
Otherwise, we continue the while loop.
Let’s run StressTest(10,100000) and keep our fingers crossed in
a hope that it outputs “Wrong answer.” We see something like this (the
result can be different on your computer because of a different random
number generator).
...
OK
67232 68874 69499
OK
6132 56210 45236 95361 68380 16906 80495 95298
OK
62180 1856 89047 14251 8362 34171 93584 87362 83341 8784
OK
19
20. 21468 16859 82178 70496 82939 44491
OK
68165 87637 74297 2904 32873 86010 87637 66131 82858 82935
Wrong answer: 7680243769 7537658370
Hurrah! We’ve found a test case where MaxPairwiseProductNaive
and MaxPairwiseProductFast produce different results, so now we can
check what went wrong. Then we can debug this solution on this test
case, find a bug, fix it, and repeat the stress test again.
Stop and Think. Do you see anything suspicious in the found dataset?
Note that generating tests automatically and running stress test is easy,
but debugging is hard. Before diving into debugging, let’s try to generate
a smaller test case to simplify it. To do that, we change N from 10 to 5
and M from 100000 to 9.
Stop and Think. Why did we first run StressTest with large parame-
ters N and M and now intend to run it with small N and M?
We then run the stress test again and it produces the following.
...
7 3 6
OK
2 9 3 1 9
Wrong answer: 81 27
The slow MaxPairwiseProductNaive gives the correct answer 81 (9 · 9 =
81), but the fast MaxPairwiseProductFast gives an incorrect answer 27.
Stop and Think. How MaxPairwiseProductFast can possibly return 27?
To debug our fast solution, let’s check which two numbers it identifies
as two largest ones. For this, we add the following line before the return
statement of the MaxPairwiseProductFast function:
print(index1, index2)
After running the stress test again, we see the following.
...
7 3 6
1 3
20
21. OK
5
2 9 3 1 9
2 3
Wrong answer: 81 27
Note that our solutions worked and then failed on exactly the same
test cases as on the previous run of the stress test, because we didn’t
change anything in the test generator. The numbers it uses to generate
tests are pseudorandom rather than random—it means that the sequence
looks random, but it is the same each time we run this program. It is
a convenient and important property, and you should try to have your
programs exhibit such behavior, because deterministic programs (that al-
ways give the same result for the same input) are easier to debug than
non-deterministic ones.
Now let’s examine index1 = 2 and index2 = 3. If we look at the code for
determining the second maximum, we will notice a subtle bug. When we
implemented a condition on i (such that it is not the same as the previ-
ous maximum) instead of comparing i and index1, we compared A[i] with
A[index1]. This ensures that the second maximum differs from the first
maximum by the value rather than by the index of the element that we
select for solving the Maximum Pairwise Product Problem. So, our solu-
tion fails on any test case where the largest number is equal to the second
largest number. We now change the condition from
A[i] , A[index1]
to
i , index1
After running the stress test again, we see a barrage of “OK” messages
on the screen. We wait for a minute until we get bored and then decide
that MaxPairwiseProductFast is finally correct!
However, you shouldn’t stop here, since you have only generated very
small tests with N = 5 and M = 10. We should check whether our pro-
gram works for larger n and larger elements of the array. So, we change
N to 1000 (for larger N, the naive solution will be pretty slow, because
its running time is quadratic). We also change M to 200000 and run. We
again see the screen filling with words “OK”, wait for a minute, and then
21
22. decide that (finally!) MaxPairwiseProductFast is correct. Afterwards, we
submit the resulting solution to the grading system and pass the Maxi-
mum Pairwise Product Problem test!
As you see, even for such a simple problems like Maximum Pairwise
Product, it is easy to make subtle mistakes when designing and imple-
menting an algorithm. The pseudocode below presents a more “reliable”
way of implementing the algorithm.
MaxPairwiseProductFast(A[1...n]):
index ← 1
for i from 2 to n:
if A[i] > A[index]:
index ← i
swap A[index] and A[n]
index ← 1
for i from 2 to n − 1:
if A[i] > A[index]:
index ← i
swap A[index] and A[n − 1]
return A[n − 1] · A[n]
In this book, besides learning how to design and analyze algorithms,
you will learn how to implement algorithms in a way that minimizes the
chances of making a mistake, and how to test your implementations.
2.6 Even Faster Algorithm
The MaxPairwiseProductFast algorithm finds the largest and the second
largest elements in about 2n comparisons.
Exercise Break. Find two largest elements in an array in 1.5n compar-
isons.
After solving this problem, try the next, even more challenging Exer-
cise Break.
Exercise Break. Find two largest elements in an array in n + dlog2 ne − 2
comparisons.
22
23. And if you feel that the previous Exercise Break was easy, here are the
next two challenges that you may face at your next interview!
Exercise Break. Prove that no algorithm for finding two largest elements
in an array can do this in less than n + dlog2 ne − 2 comparisons.
Exercise Break. What is the fastest algorithm for finding three largest
elements?
2.7 A More Compact Algorithm
The Maximum Pairwise Product Problem can be solved by the following
compact algorithm that uses sorting (in non-decreasing order).
MaxPairwiseProductBySorting(A[1...n]):
Sort(A)
return A[n − 1] · A[n]
This algorithm does more than we actually need: instead of finding two
largest elements, it sorts the entire array. For this reason, its running time
is O(nlogn), but not O(n). Still, for the given constraints (2 ≤ n ≤ 2 · 105)
this is usually sufficiently fast to fit into a second and pass our grader.
3 Solving a Programming Challenge in Five
Easy Steps
Below we summarize what we’ve learned in this chapter.
3.1 Reading Problem Statement
Start by reading the problem statement that contains the description of
a computational task, time and memory limits, and a few sample tests.
Make sure you understand how an output matches an input in each sam-
ple case.
If time and memory limits are not specified explicitly in the problem
statement, the following default values are used.
23
24. Time limits (sec.):
C C++ Java Python C# Haskell JavaScript Kotlin Ruby Rust Scala
1 1 1.5 5 1.5 2 5 1.5 5 1 3
Memory limit: 512 Mb.
3.2 Designing an Algorithm
After designing an algorithm, prove that it is correct and try to estimate
its expected running time on the most complex inputs specified in the
constraints section. If you laptop performs roughly 108–109 operations
per second, and the maximum size of a dataset in the problem description
is n = 105, then an algorithm with quadratic running time is unlikely to
fit into the time limit (since n2 = 1010), while a solution with running time
O(nlogn) will. However, an O(n2) solution will fit if n = 1000, and if
n = 100, even an O(n3) solutions will fit. Although polynomial algorithms
remain unknown for some hard problems in this book, a solution with
O(2nn2) running time will probably fit into the time limit as long as n is
smaller than 20.
3.3 Implementing an Algorithm
Start implementing your algorithm in one of the following program-
ming languages supported by our automated grading system: C, C++, C#,
Haskell, Java, JavaScript, Kotlin, Python2, Python3, Ruby, or Scala.
For all problems, we provide starter solutions for C++, Java, and Python3.
For other programming languages, you need to implement a solution from
scratch. The grading system detects the programming language of your
submission automatically, based on the extension of the submission file.
We have reference solutions in C++, Java, and Python3 (that we don’t
share with you) which solve the problem correctly under the given con-
straints, and spend at most 1/3 of the time limit and at most 1/2 of the
memory limit. You can also use other languages, and we’ve estimated the
time limit multipliers for them. However, we have no guarantee that a cor-
rect solution for a particular problem running under the given time and
memory constraints exists in any of those other languages.
24
25. In the Appendix, we list compiler versions and flags used by the grad-
ing system. We recommend using the same compiler flags when you test
your solution locally. This will increase the chances that your program be-
haves in the same way on your machine and on the testing machine (note
that a buggy program may behave differently when compiled by different
compilers, or even by the same compiler with different flags).
3.4 Testing and Debugging
Submitting your implementation to the grading system without testing
it first is a bad idea! Start with small datasets and make sure that your
program produces correct results on all sample datasets. Then proceed
to checking how long it takes to process a large dataset. To estimate the
running time, it makes sense to implement your algorithm as a function
like solve(dataset) and then implement an additional procedure gener-
ate() that produces a large dataset. For example, if an input to a problem
is a sequence of integers of length 1 ≤ n ≤ 105, then generate a sequence of
length 105, pass it to your solve() function, and ensure that the program
outputs the result quickly.
Check the boundary values to ensure that your program processes cor-
rectly both short sequences (e.g., with 2 elements) and long sequences
(e.g., with 105 elements). If a sequence of integers from 0 to, let’s say, 106
is given as an input, check how your program behaves when it is given
a sequence 0,0,...,0 or a sequence 106,106,...,106. Afterwards, check it
also on randomly generated data. Check degenerate cases like an empty
set, three points on a single line, a tree which consists of a single path of
nodes, etc.
After it appears that your program works on all these tests, proceed
to stress testing. Implement a slow, but simple and correct algorithm and
check that two programs produce the same result (note however that this
is not applicable to problems where the output is not unique). Generate
random test cases as well as biased tests cases such as those with only
small numbers or a small range of large numbers, strings containing a sin-
gle letter “a” or only two different letters (as opposed to strings composed
of all possible Latin letters), and so on. Think about other possible tests
which could be peculiar in some sense. For example, if you are generating
graphs, try generating trees, disconnected graphs, complete graphs, bipar-
tite graphs, etc. If you generate trees, try generating paths, binary trees,
25
26. stars, etc. If you are generating integers, try generating both prime and
composite numbers.
3.5 Submitting to the Grading System
When you are done with testing, submit your program to the grading sys-
tem! Go to the submission page, create a new submission, and upload a file
with your program (make sure to upload a source file rather than an exe-
cutable). The grading system then compiles your program and runs it on
a set of carefully constructed tests to check that it outputs a correct result
for all tests and that it fits into the time and memory limits. The grading
usually takes less than a minute, but in rare cases, when the servers are
overloaded, it might take longer. Please be patient. You can safely leave
the page when your solution is uploaded.
As a result, you get a feedback message from the grading system. You
want to see the “Good job!” message indicating that your program passed
all the tests. The messages “Wrong answer”, “Time limit exceeded”,
“Memory limit exceeded” notify you that your program failed due to one
of these reasons. If you program fails on one of the first two test cases, the
grader will report this to you and will show you the test case and the out-
put of your program. This is done to help you to get the input/output
format right. In all other cases, the grader will not show you the test case
where your program fails.
4 Appendix
4.1 Compiler Flags
C (gcc 7.4.0). File extensions: .c. Flags:
gcc -pipe -O2 -std=c11 <filename> -lm
C++ (g++ 7.4.0). File extensions: .cc, .cpp. Flags:
g++ -pipe -O2 -std=c++14 <filename> -lm
If your C/C++ compiler does not recognize -std=c++14 flag, try re-
placing it with -std=c++0x flag or compiling without this flag at all
26
27. (all starter solutions can be compiled without it). On Linux and Ma-
cOS, you most probably have the required compiler. On Windows,
you may use your favorite compiler or install, e.g., cygwin.
C# (mono 4.6.2). File extensions: .cs. Flags:
mcs
Go (golang 1.13.4). File extensions: .go. Flags
go
Haskell (ghc 8.0.2). File extensions: .hs. Flags:
ghc -O2
Java (OpenJDK 1.8.0 232). File extensions: .java. Flags:
javac -encoding UTF-8
java -Xmx1024m
JavaScript (NodeJS 12.14.0). File extensions: .js. No flags:
nodejs
Kotlin (Kotlin 1.3.50). File extensions: .kt. Flags:
kotlinc
java -Xmx1024m
Python (CPython 3.6.9). File extensions: .py. No flags:
python3
Ruby (Ruby 2.5.1p57). File extensions: .rb.
ruby
Rust (Rust 1.37.0). File extensions: .rs.
rustc
Scala (Scala 2.12.10). File extensions: .scala.
scalac
27
28. 4.2 Frequently Asked Questions
Why My Submission Is Not Graded?
You need to create a submission and upload the source file (rather than the
executable file) of your solution. Make sure that after uploading the file
with your solution you press the blue “Submit” button at the bottom. Af-
ter that, the grading starts, and the submission being graded is enclosed in
an orange rectangle. After the testing is finished, the rectangle disappears,
and the results of the testing of all problems are shown.
What Are the Possible Grading Outcomes?
There are only two outcomes: “pass” or “no pass.” To pass, your program
must return a correct answer on all the test cases we prepared for you, and
do so under the time and memory constraints specified in the problem
statement. If your solution passes, you get the corresponding feedback
”Good job!” and get a point for the problem. Your solution fails if it either
crashes, returns an incorrect answer, works for too long, or uses too much
memory for some test case. The feedback will contain the index of the first
test case on which your solution failed and the total number of test cases
in the system. The tests for the problem are numbered from 1 to the total
number of test cases for the problem, and the program is always tested
on all the tests in the order from the first test to the test with the largest
number.
Here are the possible outcomes:
• Good job! Hurrah! Your solution passed, and you get a point!
• Wrong answer. Your solution outputs incorrect answer for some test
case. Check that you consider all the cases correctly, avoid integer
overflow, output the required white spaces, output the floating point
numbers with the required precision, don’t output anything in addi-
tion to what you are asked to output in the output specification of
the problem statement.
• Time limit exceeded. Your solution worked longer than the al-
lowed time limit for some test case. Check again the running time of
your implementation. Test your program locally on the test of max-
imum size specified in the problem statement and check how long it
28
29. works. Check that your program doesn’t wait for some input from
the user which makes it to wait forever.
• Memory limit exceeded. Your solution used more than the al-
lowed memory limit for some test case. Estimate the amount of
memory that your program is going to use in the worst case and
check that it does not exceed the memory limit. Check that your
data structures fit into the memory limit. Check that you don’t cre-
ate large arrays or lists or vectors consisting of empty arrays or empty
strings, since those in some cases still eat up memory. Test your pro-
gram locally on the tests of maximum size specified in the problem
statement and look at its memory consumption in the system.
• Cannot check answer. Perhaps the output format is
wrong. This happens when you output something different
than expected. For example, when you are required to output
either “Yes” or “No”, but instead output 1 or 0. Or your program
has empty output. Or your program outputs not only the correct
answer, but also some additional information (please follow the
exact output format specified in the problem statement). Maybe
your program doesn’t output anything, because it crashes.
• Unknown signal 6 (or 7, or 8, or 11, or some other). This
happens when your program crashes. It can be because of a division
by zero, accessing memory outside of the array bounds, using unini-
tialized variables, overly deep recursion that triggers a stack over-
flow, sorting with a contradictory comparator, removing elements
from an empty data structure, trying to allocate too much memory,
and many other reasons. Look at your code and think about all those
possibilities. Make sure that you use the same compiler and the same
compiler flags as we do.
• Internal error: exception... Most probably, you submitted
a compiled program instead of a source code.
• Grading failed. Something wrong happened with the system. Re-
port this through Coursera or edX Help Center.
29
30. May I Post My Solution at the Forum?
Please do not post any solutions at the forum or anywhere on the web,
even if a solution does not pass the tests (as in this case you are still reveal-
ing parts of a correct solution). Our students follow the Honor Code: “I
will not make solutions to homework, quizzes, exams, projects, and other
assignments available to anyone else (except to the extent an assignment
explicitly permits sharing solutions).”
Do I Learn by Trying to Fix My Solution?
My implementation always fails in the grader, though I already tested and
stress tested it a lot. Would not it be better if you gave me a solution to this
problem or at least the test cases that you use? I will then be able to fix my code
and will learn how to avoid making mistakes. Otherwise, I do not feel that I
learn anything from solving this problem. I am just stuck.
First of all, learning from your mistakes is one of the best ways to learn.
The process of trying to invent new test cases that might fail your pro-
gram is difficult but is often enlightening. Thinking about properties of
your program makes you understand what happens inside your program
and in the general algorithm you’re studying much more.
Also, it is important to be able to find a bug in your implementation
without knowing a test case and without having a reference solution, just
like in real life. Assume that you designed an application and an annoyed
user reports that it crashed. Most probably, the user will not tell you the
exact sequence of operations that led to a crash. Moreover, there will be
no reference application. Hence, it is important to learn how to find a bug
in your implementation yourself, without a magic oracle giving you either
a test case that your program fails or a reference solution. We encourage
you to use programming assignments in this class as a way of practicing
this important skill.
If you have already tested your program on all corner cases you can
imagine, constructed a set of manual test cases, applied stress testing, etc,
but your program still fails, try to ask for help on the forum. We encour-
age you to do this by first explaining what kind of corner cases you have
already considered (it may happen that by writing such a post you will
realize that you missed some corner cases!), and only afterwards asking
other learners to give you more ideas for tests cases.
30