Rapid urbanization and global climate change are likely to exacerbate urban flooding intensity, frequency, and uncertainty. Thus, it is fundamental and crucial to investigate the dominant influencing factors for the mitigation of urban flooding. However, the influence of building patterns on urban flooding remains limited. Taking Beijing, a typical megacity, as a case study area, we quantified the importance of building patterns and their interaction effect at the subwatershed scale using the boosted regression tree (BRT) and geographical detector model (GeoD). The results indicated that (1) the landscape shape index, slope, green space ratio and waterbody ratio were the most important influencing factors determining urban flooding, with a total relative contribution of 67.23%, (2) building metrics had a certain impact on urban flooding, and the sum of the relative contribution can reach 21.03%, (3) with urban flooding density, the landscape shape index, slope, and green space ratio exhibited a combination of negative and positive correlation, and (4) an enhancement effect existed between building metrics, especially the building congestion degree and building density. These findings provide quantitative insights that rational urban morphology planning can improve stormwater management and promote urban sustainability in megacities.